From 78ea24efcc24ef9881a7446f0ff8bfdca594d0ff Mon Sep 17 00:00:00 2001 From: Tomo Suzuki Date: Wed, 20 May 2026 17:56:37 +0000 Subject: [PATCH] feat: update API sources and regenerate --- librarian.yaml | 4 +- .../google/ads/datamanager/__init__.py | 5 +- .../google/ads/datamanager_v1/__init__.py | 5 +- .../partner_link_service/transports/base.py | 5 +- .../ads/datamanager_v1/types/__init__.py | 4 + .../ads/datamanager_v1/types/cart_data.py | 99 + .../ads/datamanager_v1/types/device_info.py | 65 + .../google/ads/datamanager_v1/types/error.py | 57 + .../google/ads/datamanager_v1/types/event.py | 93 +- .../datamanager_v1/types/processing_errors.py | 8 +- .../types/request_status_per_destination.py | 39 +- .../ads/datamanager_v1/types/user_list.py | 14 + .../test_partner_link_service.py | 25 +- .../datamanager_v1/test_user_list_service.py | 4 + .../cloud/bigquery_migration/__init__.py | 10 + .../cloud/bigquery_migration_v2/__init__.py | 7 + .../bigquery_migration_v2/types/__init__.py | 10 + .../types/assessment_task.py | 102 + .../types/migration_entities.py | 92 +- .../types/translation_details.py | 90 + .../test_migration_service.py | 1 + .../google-cloud-bigquery/docs/README.rst | 4 +- .../cloud/compute_v1beta/types/compute.py | 5 + .../global_vm_extension_policies.rst | 10 + .../docs/compute_v1/rollout_plans.rst | 10 + .../docs/compute_v1/rollouts.rst | 10 + .../docs/compute_v1/services_.rst | 3 + .../google/cloud/compute/__init__.py | 102 + .../google/cloud/compute_v1/__init__.py | 100 + .../cloud/compute_v1/gapic_metadata.json | 112 + .../global_vm_extension_policies/__init__.py | 18 + .../global_vm_extension_policies/client.py | 2015 ++++++ .../global_vm_extension_policies/pagers.py | 196 + .../transports/README.rst | 10 + .../transports/__init__.py | 33 + .../transports/base.py | 300 + .../transports/rest.py | 1572 +++++ .../transports/rest_base.py | 399 ++ .../services/license_codes/client.py | 320 + .../services/license_codes/transports/base.py | 39 +- .../services/license_codes/transports/rest.py | 576 ++ .../license_codes/transports/rest_base.py | 102 + .../compute_v1/services/networks/client.py | 316 + .../services/networks/transports/base.py | 14 + .../services/networks/transports/rest.py | 252 + .../services/networks/transports/rest_base.py | 56 + .../services/rollout_plans/__init__.py | 18 + .../services/rollout_plans/client.py | 1506 ++++ .../services/rollout_plans/pagers.py | 117 + .../rollout_plans/transports/README.rst | 10 + .../rollout_plans/transports/__init__.py | 30 + .../services/rollout_plans/transports/base.py | 257 + .../services/rollout_plans/transports/rest.py | 1090 +++ .../rollout_plans/transports/rest_base.py | 285 + .../compute_v1/services/rollouts/__init__.py | 18 + .../compute_v1/services/rollouts/client.py | 1514 ++++ .../compute_v1/services/rollouts/pagers.py | 117 + .../services/rollouts/transports/README.rst | 10 + .../services/rollouts/transports/__init__.py | 30 + .../services/rollouts/transports/base.py | 253 + .../services/rollouts/transports/rest.py | 1060 +++ .../services/rollouts/transports/rest_base.py | 275 + .../zone_vm_extension_policies/client.py | 14 +- .../google/cloud/compute_v1/types/__init__.py | 94 + .../google/cloud/compute_v1/types/compute.py | 6274 +++++++++++++---- ...extension_policies_aggregated_list_sync.py | 54 + ...lobal_vm_extension_policies_delete_sync.py | 54 + ...d_global_vm_extension_policies_get_sync.py | 54 + ...lobal_vm_extension_policies_insert_sync.py | 53 + ..._global_vm_extension_policies_list_sync.py | 54 + ...lobal_vm_extension_policies_update_sync.py | 54 + ...rated_license_codes_get_iam_policy_sync.py | 54 + ...rated_license_codes_set_iam_policy_sync.py | 54 + ...orks_cancel_request_remove_peering_sync.py | 54 + ..._v1_generated_rollout_plans_delete_sync.py | 54 + ...ute_v1_generated_rollout_plans_get_sync.py | 54 + ..._v1_generated_rollout_plans_insert_sync.py | 53 + ...te_v1_generated_rollout_plans_list_sync.py | 54 + ...mpute_v1_generated_rollouts_cancel_sync.py | 54 + ...mpute_v1_generated_rollouts_delete_sync.py | 54 + .../compute_v1_generated_rollouts_get_sync.py | 54 + ...compute_v1_generated_rollouts_list_sync.py | 54 + ...ppet_metadata_google.cloud.compute.v1.json | 3408 ++++++--- .../unit/gapic/compute_v1/test_autoscalers.py | 3 + .../test_global_vm_extension_policies.py | 5033 +++++++++++++ .../gapic/compute_v1/test_license_codes.py | 1014 ++- .../unit/gapic/compute_v1/test_networks.py | 710 ++ .../compute_v1/test_region_autoscalers.py | 3 + .../compute_v1/test_region_ssl_policies.py | 4 + .../gapic/compute_v1/test_rollout_plans.py | 3635 ++++++++++ .../unit/gapic/compute_v1/test_rollouts.py | 3492 +++++++++ .../gapic/compute_v1/test_ssl_policies.py | 4 + .../google/cloud/databasecenter/__init__.py | 12 + .../cloud/databasecenter_v1beta/__init__.py | 12 + .../databasecenter_v1beta/gapic_metadata.json | 15 + .../services/database_center/async_client.py | 105 + .../services/database_center/client.py | 103 + .../services/database_center/pagers.py | 156 + .../database_center/transports/base.py | 17 + .../database_center/transports/grpc.py | 29 + .../transports/grpc_asyncio.py | 35 + .../database_center/transports/rest.py | 226 + .../database_center/transports/rest_base.py | 67 + .../databasecenter_v1beta/types/__init__.py | 12 + .../databasecenter_v1beta/types/service.py | 305 + ...base_center_aggregate_query_stats_async.py | 54 + ...abase_center_aggregate_query_stats_sync.py | 54 + ...ta_google.cloud.databasecenter.v1beta.json | 153 + .../test_database_center.py | 918 ++- .../google/cloud/storage/bucket.py | 3 +- .../tests/system/test_zonal.py | 8 +- .../asyncio/test_async_write_object_stream.py | 2 +- 112 files changed, 38205 insertions(+), 2588 deletions(-) create mode 100644 packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/assessment_task.py create mode 100644 packages/google-cloud-compute/docs/compute_v1/global_vm_extension_policies.rst create mode 100644 packages/google-cloud-compute/docs/compute_v1/rollout_plans.rst create mode 100644 packages/google-cloud-compute/docs/compute_v1/rollouts.rst create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/client.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/pagers.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/README.rst create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/rest.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/rest_base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/client.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/pagers.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/README.rst create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/rest.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/rest_base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/client.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/pagers.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/README.rst create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/__init__.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/base.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest.py create mode 100644 packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest_base.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_aggregated_list_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_delete_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_get_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_insert_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_list_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_update_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_license_codes_get_iam_policy_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_license_codes_set_iam_policy_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_networks_cancel_request_remove_peering_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_delete_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_get_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_insert_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_list_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_cancel_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_delete_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_get_sync.py create mode 100644 packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_list_sync.py create mode 100644 packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_vm_extension_policies.py create mode 100644 packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollout_plans.py create mode 100644 packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollouts.py create mode 100644 packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_query_stats_async.py create mode 100644 packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_query_stats_sync.py diff --git a/librarian.yaml b/librarian.yaml index 18d5411689c9..9a2d5f09fcd5 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.14.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: 84009fb6ad8975910a5cb62d32e7f35e48c9da02 - sha256: b82e61ef9bc042fe02c9c9113a53d207331dc7cd8c10cc0d4f4cbeb7e65f1577 + commit: 43731d5d22f8e3526ba7aa708da9d5de26043d0f + sha256: d146cfa257ffa00fc298ec7b6f73f9c7395a5a5ba050dcc553cfd78d6705bc3b default: output: packages tag_format: '{name}-v{version}' diff --git a/packages/google-ads-datamanager/google/ads/datamanager/__init__.py b/packages/google-ads-datamanager/google/ads/datamanager/__init__.py index 79e4781ad9c7..e722315dcb87 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager/__init__.py +++ b/packages/google-ads-datamanager/google/ads/datamanager/__init__.py @@ -62,7 +62,7 @@ PpidData, UserIdData, ) -from google.ads.datamanager_v1.types.cart_data import CartData, Item +from google.ads.datamanager_v1.types.cart_data import CartData, Item, ItemCustomVariable from google.ads.datamanager_v1.types.consent import Consent, ConsentStatus from google.ads.datamanager_v1.types.destination import ( Destination, @@ -80,6 +80,7 @@ AdIdentifiers, CustomVariable, Event, + EventLocation, EventParameter, EventSource, ) @@ -217,6 +218,7 @@ "UserIdData", "CartData", "Item", + "ItemCustomVariable", "Consent", "ConsentStatus", "Destination", @@ -230,6 +232,7 @@ "AdIdentifiers", "CustomVariable", "Event", + "EventLocation", "EventParameter", "EventSource", "ExperimentalField", diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/__init__.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/__init__.py index 75c46a770e98..2e45c6a0ee50 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/__init__.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/__init__.py @@ -49,7 +49,7 @@ ) from .types.age_range import AgeRange from .types.audience import AudienceMember, MobileData, PairData, PpidData, UserIdData -from .types.cart_data import CartData, Item +from .types.cart_data import CartData, Item, ItemCustomVariable from .types.consent import Consent, ConsentStatus from .types.destination import Destination, Product, ProductAccount from .types.device_info import DeviceInfo @@ -59,6 +59,7 @@ AdIdentifiers, CustomVariable, Event, + EventLocation, EventParameter, EventSource, ) @@ -274,6 +275,7 @@ def _get_version(dependency_name): "ErrorInfo", "ErrorReason", "Event", + "EventLocation", "EventParameter", "EventSource", "ExperimentalField", @@ -289,6 +291,7 @@ def _get_version(dependency_name): "IngestedUserListInfo", "IngestionServiceClient", "Item", + "ItemCustomVariable", "ItemParameter", "ListUserListDirectLicensesRequest", "ListUserListDirectLicensesResponse", diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/transports/base.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/transports/base.py index 12f64de82b7d..f9deaa19117e 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/transports/base.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/services/partner_link_service/transports/base.py @@ -40,7 +40,10 @@ class PartnerLinkServiceTransport(abc.ABC): """Abstract transport class for PartnerLinkService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/datamanager",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/datamanager", + "https://www.googleapis.com/auth/datamanager.partnerlink", + ) DEFAULT_HOST: str = "datamanager.googleapis.com" diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/__init__.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/__init__.py index 2c29073d7922..85cd0e039d1e 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/__init__.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/__init__.py @@ -26,6 +26,7 @@ from .cart_data import ( CartData, Item, + ItemCustomVariable, ) from .consent import ( Consent, @@ -51,6 +52,7 @@ AdIdentifiers, CustomVariable, Event, + EventLocation, EventParameter, EventSource, ) @@ -184,6 +186,7 @@ "UserIdData", "CartData", "Item", + "ItemCustomVariable", "Consent", "ConsentStatus", "Destination", @@ -197,6 +200,7 @@ "AdIdentifiers", "CustomVariable", "Event", + "EventLocation", "EventParameter", "EventSource", "ExperimentalField", diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/cart_data.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/cart_data.py index 44b6922b9a6c..f250cb49dda4 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/cart_data.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/cart_data.py @@ -26,6 +26,7 @@ manifest={ "CartData", "Item", + "ItemCustomVariable", }, ) @@ -50,6 +51,15 @@ class CartData(proto.Message): items (MutableSequence[google.ads.datamanager_v1.types.Item]): Optional. The list of items associated with the event. + coupon_codes (MutableSequence[str]): + Optional. The list of coupon codes that were + applied to the cart. Cart-level and item-level + coupon codes are independent. + + If the event is for a Google Analytics + destination, only provide a single coupon code. + Google Analytics ignores additional coupon + codes. """ merchant_id: str = proto.Field( @@ -73,11 +83,17 @@ class CartData(proto.Message): number=5, message="Item", ) + coupon_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) class Item(proto.Message): r"""Represents an item in the cart associated with the event. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: merchant_product_id (str): Optional. The product ID within the Merchant @@ -96,6 +112,34 @@ class Item(proto.Message): item `__ to be included within the event that were not already specified using other structured fields. + merchant_id (str): + Optional. The Merchant Center ID associated + with the item. For Store Sales events this will + override the value set at the cart level. This + field is ignored for other events. + merchant_feed_label (str): + Optional. The feed label of the Merchant + Center feed. If countries are still being used, + the 2-letter country code in ISO-3166-1 alpha-2 + can be used instead. For Store Sales events this + will override the value set at the cart level. + This field is ignored for other events. + merchant_feed_language_code (str): + Optional. The language code in ISO 639-1 + associated with the Merchant Center feed where + your items are uploaded. + conversion_value (float): + Optional. The conversion value associated + with this item within the event, for cases where + the conversion value is different for each item. + + This field is a member of `oneof`_ ``_conversion_value``. + custom_variables (MutableSequence[google.ads.datamanager_v1.types.ItemCustomVariable]): + Optional. Additional key/value pair + information to send to the conversion containers + (conversion action or Floodlight activity), when + tracking per-item + conversions. """ merchant_product_id: str = proto.Field( @@ -121,6 +165,61 @@ class Item(proto.Message): message=item_parameter.ItemParameter, ) ) + merchant_id: str = proto.Field( + proto.STRING, + number=6, + ) + merchant_feed_label: str = proto.Field( + proto.STRING, + number=7, + ) + merchant_feed_language_code: str = proto.Field( + proto.STRING, + number=8, + ) + conversion_value: float = proto.Field( + proto.DOUBLE, + number=9, + optional=True, + ) + custom_variables: MutableSequence["ItemCustomVariable"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="ItemCustomVariable", + ) + + +class ItemCustomVariable(proto.Message): + r"""Item-level custom variable for ads conversions. + + Attributes: + variable (str): + Optional. The name of the custom variable to + set. If the variable is not found for the given + destination, it will be ignored. + value (str): + Optional. The value to store for the custom + variable. + destination_references (MutableSequence[str]): + Optional. Reference string used to determine which of the + [Event.destination_references][google.ads.datamanager.v1.Event.destination_references] + the custom variable should be sent to. If empty, the + [Event.destination_references][google.ads.datamanager.v1.Event.destination_references] + will be used. + """ + + variable: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + destination_references: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/device_info.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/device_info.py index d0724f61e013..d8d924e58dd7 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/device_info.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/device_info.py @@ -50,6 +50,31 @@ class DeviceInfo(proto.Message): `About offline conversion imports `__ page for more details. + category (str): + Optional. The category of device. For + example, “desktop”, “tablet”, “mobile”, “smart + TV”. + language_code (str): + Optional. The language the device uses in ISO + 639-1 format. + screen_height (int): + Optional. The height of the screen in pixels. + screen_width (int): + Optional. The width of the screen in pixels. + operating_system (str): + Optional. The operating system or platform of + the device. + operating_system_version (str): + Optional. The version of the operating system + or platform. + model (str): + Optional. The model of the device. + brand (str): + Optional. The brand of the device. + browser (str): + Optional. The brand or type of the browser. + browser_version (str): + Optional. The version of the browser. """ user_agent: str = proto.Field( @@ -60,6 +85,46 @@ class DeviceInfo(proto.Message): proto.STRING, number=2, ) + category: str = proto.Field( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + screen_height: int = proto.Field( + proto.INT32, + number=5, + ) + screen_width: int = proto.Field( + proto.INT32, + number=6, + ) + operating_system: str = proto.Field( + proto.STRING, + number=7, + ) + operating_system_version: str = proto.Field( + proto.STRING, + number=8, + ) + model: str = proto.Field( + proto.STRING, + number=9, + ) + brand: str = proto.Field( + proto.STRING, + number=10, + ) + browser: str = proto.Field( + proto.STRING, + number=11, + ) + browser_version: str = proto.Field( + proto.STRING, + number=12, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py index 6a53e88b0aff..7319d31924d9 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py @@ -302,6 +302,46 @@ class ErrorReason(proto.Enum): The customer contains non-exempt campaigns without the EU political advertising declaration. + ACCOUNT_INELIGIBLE_FOR_STORE_SALES (102): + Account is not eligible for Store Sales. + INVALID_MERCHANT_FEED_LANGUAGE_CODE (103): + The merchant feed language code is not valid. + INVALID_REGION_CODE (104): + The region code is not valid. + INVALID_SUBDIVISION_CODE (107): + The subdivision code is not valid. + INVALID_SUBCONTINENT_CODE (108): + The subcontinent code is not valid. + INVALID_CONTINENT_CODE (109): + The continent code is not valid. + INVALID_DEVICE_CATEGORY (110): + The device category is not valid. + BOTH_CLIENT_ID_AND_APP_INSTANCE_ID_NOT_ALLOWED (111): + Both app_instance_id and client_id are set. + GOOGLE_ANALYTICS_SUBPROPERTY_OR_ROLLUP_PROPERTY_NOT_ALLOWED (112): + The Google Analytics property is a + subproperty or rollup property. + THIRD_PARTY_USER_DATA_NOT_ALLOWED (113): + Third party user data can only be set by data + partners. + INVALID_COUPON_CODE (114): + The coupon code is not valid. + EVENT_SOURCE_AND_DESTINATION_MISMATCH (115): + The event source type does not match the + destination type. + DESTINATION_ACCOUNT_TYPE_MISMATCH (116): + The destination account type does not match + the specified account id. + CUSTOM_VARIABLE_VALUE_CONTAINS_PII (117): + The custom variable value contains personally + identifiable information (PII). + CUSTOM_VARIABLE_NOT_ENABLED (118): + The custom variable is not enabled. + INVALID_CUSTOM_VARIABLE_VALUE (119): + The custom variable's value is invalid. + CUSTOM_VARIABLE_NOT_FOUND (120): + The destination does not have a custom variable with a name + that matches the specified ``variable``. """ ERROR_REASON_UNSPECIFIED = 0 @@ -406,6 +446,23 @@ class ErrorReason(proto.Enum): MEMBERSHIP_DURATION_TOO_LONG = 99 INVALID_MERCHANT_ID = 100 EU_POLITICAL_ADVERTISING_DECLARATION_REQUIRED = 101 + ACCOUNT_INELIGIBLE_FOR_STORE_SALES = 102 + INVALID_MERCHANT_FEED_LANGUAGE_CODE = 103 + INVALID_REGION_CODE = 104 + INVALID_SUBDIVISION_CODE = 107 + INVALID_SUBCONTINENT_CODE = 108 + INVALID_CONTINENT_CODE = 109 + INVALID_DEVICE_CATEGORY = 110 + BOTH_CLIENT_ID_AND_APP_INSTANCE_ID_NOT_ALLOWED = 111 + GOOGLE_ANALYTICS_SUBPROPERTY_OR_ROLLUP_PROPERTY_NOT_ALLOWED = 112 + THIRD_PARTY_USER_DATA_NOT_ALLOWED = 113 + INVALID_COUPON_CODE = 114 + EVENT_SOURCE_AND_DESTINATION_MISMATCH = 115 + DESTINATION_ACCOUNT_TYPE_MISMATCH = 116 + CUSTOM_VARIABLE_VALUE_CONTAINS_PII = 117 + CUSTOM_VARIABLE_NOT_ENABLED = 118 + INVALID_CUSTOM_VARIABLE_VALUE = 119 + CUSTOM_VARIABLE_NOT_FOUND = 120 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py index 4337887d9d27..a61ad69adb3f 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py @@ -34,6 +34,7 @@ "AdIdentifiers", "CustomVariable", "EventParameter", + "EventLocation", }, ) @@ -54,6 +55,8 @@ class EventSource(proto.Enum): transaction. PHONE (4): The event was generated from a phone call. + MESSAGE (6): + The event was generated from a message. OTHER (5): The event was generated from other sources. """ @@ -63,6 +66,7 @@ class EventSource(proto.Enum): APP = 2 IN_STORE = 3 PHONE = 4 + MESSAGE = 6 OTHER = 5 @@ -81,8 +85,8 @@ class Event(proto.Message): in the request. transaction_id (str): Optional. The unique identifier for this - event. Required for conversions using multiple - data sources. + event. Required for events sent as an additional + data source for tag conversions. event_timestamp (google.protobuf.timestamp_pb2.Timestamp): Required. The time the event occurred. last_updated_timestamp (google.protobuf.timestamp_pb2.Timestamp): @@ -145,6 +149,17 @@ class Event(proto.Message): parameters `__ to be included within the event that were not already specified using other structured fields. + third_party_user_data (google.ads.datamanager_v1.types.UserData): + Optional. The same type of data provided in user_data, but + explicitly flagged as being provided as owned by a + third-party and not first-party advertiser data. + event_location (google.ads.datamanager_v1.types.EventLocation): + Optional. Information gathered about the + location of the user when this event occurred. + app_instance_id (str): + Optional. A unique identifier for the user + instance of an app client for this GA4 app + stream. """ destination_references: MutableSequence[str] = proto.RepeatedField( @@ -240,6 +255,20 @@ class Event(proto.Message): message="EventParameter", ) ) + third_party_user_data: gad_user_data.UserData = proto.Field( + proto.MESSAGE, + number=20, + message=gad_user_data.UserData, + ) + event_location: "EventLocation" = proto.Field( + proto.MESSAGE, + number=21, + message="EventLocation", + ) + app_instance_id: str = proto.Field( + proto.STRING, + number=22, + ) class AdIdentifiers(proto.Message): @@ -266,6 +295,11 @@ class AdIdentifiers(proto.Message): device being used (if any) at the time of landing onto the advertiser’s site after interacting with the ad. + mobile_device_id (str): + Optional. The mobile identifier for + advertisers. This would be IDFA on iOS, AdID on + Android, or other platforms’ identifiers for + advertisers. """ session_attributes: str = proto.Field( @@ -289,6 +323,10 @@ class AdIdentifiers(proto.Message): number=5, message=device_info.DeviceInfo, ) + mobile_device_id: str = proto.Field( + proto.STRING, + number=6, + ) class CustomVariable(proto.Message): @@ -345,4 +383,55 @@ class EventParameter(proto.Message): ) +class EventLocation(proto.Message): + r"""The location where the event occurred. + + Attributes: + store_id (str): + Optional. Required for Store Sales. The + identifier to represent a physical store where + the event happened. + city (str): + Optional. The name of the city where the + event occurred. + subdivision_code (str): + Optional. The ISO 3166-2 subdivision code + where the event occurred. + region_code (str): + Optional. The 2-letter CLDR region code of + the user's address. + subcontinent_code (str): + Optional. The subcontinent code in UN M49 + format where the event occurred. + continent_code (str): + Optional. The continent code in UN M49 format + where the event occurred. + """ + + store_id: str = proto.Field( + proto.STRING, + number=1, + ) + city: str = proto.Field( + proto.STRING, + number=2, + ) + subdivision_code: str = proto.Field( + proto.STRING, + number=3, + ) + region_code: str = proto.Field( + proto.STRING, + number=4, + ) + subcontinent_code: str = proto.Field( + proto.STRING, + number=5, + ) + continent_code: str = proto.Field( + proto.STRING, + number=6, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/processing_errors.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/processing_errors.py index 9bf8f597a02b..8cfa63f65e7c 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/processing_errors.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/processing_errors.py @@ -113,6 +113,9 @@ class ProcessingErrorReason(proto.Enum): The user attempted to ingest events with an ad identifier that isn't from the operating account's ads. + PROCESSING_ERROR_REASON_ONE_PER_CLICK_CONVERSION_ACTION_NOT_PERMITTED_WITH_BRAID (28): + One-per-click conversion actions cannot be + used with BRAIDs. """ PROCESSING_ERROR_REASON_UNSPECIFIED = 0 @@ -143,6 +146,9 @@ class ProcessingErrorReason(proto.Enum): PROCESSING_ERROR_REASON_AWS_AUTH_FAILED = 27 PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR = 25 PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER = 26 + PROCESSING_ERROR_REASON_ONE_PER_CLICK_CONVERSION_ACTION_NOT_PERMITTED_WITH_BRAID = ( + 28 + ) class ProcessingWarningReason(proto.Enum): @@ -168,7 +174,7 @@ class ProcessingWarningReason(proto.Enum): The KEK cannot decrypt data because it is the wrong KEK, or it does not exist. PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR (7): - Failed to decrypt th + Failed to decrypt the [UserIdentifier][google.ads.datamanager.v1.UserIdentifier] data using the DEK. PROCESSING_WARNING_REASON_INTERNAL_ERROR (8): diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/request_status_per_destination.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/request_status_per_destination.py index a596c58d078a..21dc6fee79bb 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/request_status_per_destination.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/request_status_per_destination.py @@ -46,11 +46,24 @@ class RequestStatusPerDestination(proto.Message): request_status (google.ads.datamanager_v1.types.RequestStatusPerDestination.RequestStatus): The request status of the destination. error_info (google.ads.datamanager_v1.types.ErrorInfo): - An error info error containing the error - reason and error counts related to the upload. + An error info error containing the error reason and error + counts related to the upload. Only populated if the + [``request_status``][google.ads.datamanager.v1.RequestStatusPerDestination.request_status] + is + [``FAILED``][google.ads.datamanager.v1.RequestStatusPerDestination.RequestStatus.FAILED] + or + [``PARTIAL_SUCCESS``][google.ads.datamanager.v1.RequestStatusPerDestination.RequestStatus.PARTIAL_SUCCESS]. + This field isn't populated while the request has + [``request_status``][google.ads.datamanager.v1.RequestStatusPerDestination.request_status] + of + [``PROCESSING``][google.ads.datamanager.v1.RequestStatusPerDestination.RequestStatus.PROCESSING]. warning_info (google.ads.datamanager_v1.types.WarningInfo): - A warning info containing the warning reason - and warning counts related to the upload. + A warning info containing the warning reason and warning + counts related to the upload. This field isn't populated + while the request has + [``request_status``][google.ads.datamanager.v1.RequestStatusPerDestination.request_status] + of + [``PROCESSING``][google.ads.datamanager.v1.RequestStatusPerDestination.RequestStatus.PROCESSING]. audience_members_ingestion_status (google.ads.datamanager_v1.types.RequestStatusPerDestination.IngestAudienceMembersStatus): The status of the ingest audience members request. @@ -74,13 +87,25 @@ class RequestStatus(proto.Enum): REQUEST_STATUS_UNKNOWN (0): The request status is unknown. SUCCESS (1): - The request succeeded. + Processing succeeded for all records without any errors. + However, there may be warnings in the + [``warning_info``][google.ads.datamanager.v1.RequestStatusPerDestination.warning_info] + field. PROCESSING (2): The request is processing. FAILED (3): - The request failed. + Processing failed for all records. Check the + [``error_info``][google.ads.datamanager.v1.RequestStatusPerDestination.error_info] + field for error details, and check the + [``warning_info``][google.ads.datamanager.v1.RequestStatusPerDestination.warning_info] + field for warning details. PARTIAL_SUCCESS (4): - The request partially succeeded. + Processing completed successfully without errors for some + records, but failed with errors for other records. Check the + [``error_info``][google.ads.datamanager.v1.RequestStatusPerDestination.error_info] + field for error details, and check the + [``warning_info``][google.ads.datamanager.v1.RequestStatusPerDestination.warning_info] + field for warning details. """ REQUEST_STATUS_UNKNOWN = 0 diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/user_list.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/user_list.py index 9d7f7fdb02eb..4a5e8ec906c9 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/user_list.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/user_list.py @@ -291,6 +291,12 @@ class SizeInfo(proto.Message): this user list in the google.com domain. These are the members available for targeting in Search campaigns. + youtube_members_count (int): + Output only. Estimated number of members in + this user list on YouTube. + gmail_members_count (int): + Output only. Estimated number of members in + this user list on Gmail. """ display_network_members_count: int = proto.Field( @@ -301,6 +307,14 @@ class SizeInfo(proto.Message): proto.INT64, number=2, ) + youtube_members_count: int = proto.Field( + proto.INT64, + number=3, + ) + gmail_members_count: int = proto.Field( + proto.INT64, + number=4, + ) class TargetNetworkInfo(proto.Message): diff --git a/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_partner_link_service.py b/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_partner_link_service.py index 8bdb43d84c3a..420a103e92f1 100644 --- a/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_partner_link_service.py +++ b/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_partner_link_service.py @@ -1338,7 +1338,10 @@ def test_partner_link_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/datamanager",), + default_scopes=( + "https://www.googleapis.com/auth/datamanager", + "https://www.googleapis.com/auth/datamanager.partnerlink", + ), scopes=None, default_host="datamanager.googleapis.com", ssl_credentials=None, @@ -4104,7 +4107,10 @@ def test_partner_link_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/datamanager",), + default_scopes=( + "https://www.googleapis.com/auth/datamanager", + "https://www.googleapis.com/auth/datamanager.partnerlink", + ), quota_project_id="octopus", ) @@ -4130,7 +4136,10 @@ def test_partner_link_service_auth_adc(): PartnerLinkServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/datamanager",), + default_scopes=( + "https://www.googleapis.com/auth/datamanager", + "https://www.googleapis.com/auth/datamanager.partnerlink", + ), quota_project_id=None, ) @@ -4150,7 +4159,10 @@ def test_partner_link_service_transport_auth_adc(transport_class): transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/datamanager",), + default_scopes=( + "https://www.googleapis.com/auth/datamanager", + "https://www.googleapis.com/auth/datamanager.partnerlink", + ), quota_project_id="octopus", ) @@ -4203,7 +4215,10 @@ def test_partner_link_service_transport_create_channel(transport_class, grpc_hel credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/datamanager",), + default_scopes=( + "https://www.googleapis.com/auth/datamanager", + "https://www.googleapis.com/auth/datamanager.partnerlink", + ), scopes=["1", "2"], default_host="datamanager.googleapis.com", ssl_credentials=None, diff --git a/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_user_list_service.py b/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_user_list_service.py index a4788130325f..7466e3cd0ed3 100644 --- a/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_user_list_service.py +++ b/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_user_list_service.py @@ -4997,6 +4997,8 @@ def test_create_user_list_rest_call_success(request_type): "size_info": { "display_network_members_count": 3121, "search_network_members_count": 2993, + "youtube_members_count": 2271, + "gmail_members_count": 2012, }, "target_network_info": { "eligible_for_display": True, @@ -5260,6 +5262,8 @@ def test_update_user_list_rest_call_success(request_type): "size_info": { "display_network_members_count": 3121, "search_network_members_count": 2993, + "youtube_members_count": 2271, + "gmail_members_count": 2012, }, "target_network_info": { "eligible_for_display": True, diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration/__init__.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration/__init__.py index b3caf38d985a..e5b0ee56c099 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration/__init__.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration/__init__.py @@ -24,6 +24,10 @@ from google.cloud.bigquery_migration_v2.services.migration_service.client import ( MigrationServiceClient, ) +from google.cloud.bigquery_migration_v2.types.assessment_task import ( + AssessmentFeatureHandle, + AssessmentTaskDetails, +) from google.cloud.bigquery_migration_v2.types.migration_entities import ( MigrationSubtask, MigrationTask, @@ -84,6 +88,8 @@ SourceEnvironment, SourceSpec, SourceTargetMapping, + SuggestionConfig, + SuggestionStep, TargetSpec, TranslationDetails, ) @@ -97,6 +103,8 @@ __all__ = ( "MigrationServiceClient", "MigrationServiceAsyncClient", + "AssessmentFeatureHandle", + "AssessmentTaskDetails", "MigrationSubtask", "MigrationTask", "MigrationTaskResult", @@ -146,6 +154,8 @@ "SourceEnvironment", "SourceSpec", "SourceTargetMapping", + "SuggestionConfig", + "SuggestionStep", "TargetSpec", "TranslationDetails", "TranslationReportRecord", diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/__init__.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/__init__.py index dfc2d20f8f1a..e634458e23ef 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/__init__.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/__init__.py @@ -27,6 +27,7 @@ MigrationServiceAsyncClient, MigrationServiceClient, ) +from .types.assessment_task import AssessmentFeatureHandle, AssessmentTaskDetails from .types.migration_entities import ( MigrationSubtask, MigrationTask, @@ -82,6 +83,8 @@ SourceEnvironment, SourceSpec, SourceTargetMapping, + SuggestionConfig, + SuggestionStep, TargetSpec, TranslationDetails, ) @@ -173,6 +176,8 @@ def _get_version(dependency_name): __all__ = ( "MigrationServiceAsyncClient", + "AssessmentFeatureHandle", + "AssessmentTaskDetails", "AzureSynapseDialect", "BigQueryDialect", "CreateMigrationWorkflowRequest", @@ -217,6 +222,8 @@ def _get_version(dependency_name): "SourceTargetMapping", "SparkSQLDialect", "StartMigrationWorkflowRequest", + "SuggestionConfig", + "SuggestionStep", "TargetSpec", "TeradataDialect", "TimeInterval", diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/__init__.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/__init__.py index fddf22e90828..bba470921c0a 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/__init__.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .assessment_task import ( + AssessmentFeatureHandle, + AssessmentTaskDetails, +) from .migration_entities import ( MigrationSubtask, MigrationTask, @@ -73,6 +77,8 @@ SourceEnvironment, SourceSpec, SourceTargetMapping, + SuggestionConfig, + SuggestionStep, TargetSpec, TranslationDetails, ) @@ -84,6 +90,8 @@ ) __all__ = ( + "AssessmentFeatureHandle", + "AssessmentTaskDetails", "MigrationSubtask", "MigrationTask", "MigrationTaskResult", @@ -133,6 +141,8 @@ "SourceEnvironment", "SourceSpec", "SourceTargetMapping", + "SuggestionConfig", + "SuggestionStep", "TargetSpec", "TranslationDetails", "TranslationReportRecord", diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/assessment_task.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/assessment_task.py new file mode 100644 index 000000000000..9aedd35aec51 --- /dev/null +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/assessment_task.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.bigquery.migration.v2", + manifest={ + "AssessmentTaskDetails", + "AssessmentFeatureHandle", + }, +) + + +class AssessmentTaskDetails(proto.Message): + r"""Assessment task config. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + input_path (str): + Required. The Cloud Storage path for + assessment input files. + output_dataset (str): + Required. The BigQuery dataset for output. + querylogs_path (str): + Optional. An optional Cloud Storage path to + write the query logs (which is then used as an + input path on the translation task) + data_source (str): + Required. The data source or data warehouse + type (eg: TERADATA/REDSHIFT) from which the + input data is extracted. + feature_handle (google.cloud.bigquery_migration_v2.types.AssessmentFeatureHandle): + Optional. A collection of additional feature + flags for this assessment. + + This field is a member of `oneof`_ ``_feature_handle``. + """ + + input_path: str = proto.Field( + proto.STRING, + number=1, + ) + output_dataset: str = proto.Field( + proto.STRING, + number=2, + ) + querylogs_path: str = proto.Field( + proto.STRING, + number=3, + ) + data_source: str = proto.Field( + proto.STRING, + number=4, + ) + feature_handle: "AssessmentFeatureHandle" = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message="AssessmentFeatureHandle", + ) + + +class AssessmentFeatureHandle(proto.Message): + r"""User-definable feature flags for assessment tasks. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + add_shareable_dataset (bool): + Optional. Whether to create a dataset + containing non-PII data in addition to the + output dataset. + + This field is a member of `oneof`_ ``_add_shareable_dataset``. + """ + + add_shareable_dataset: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/migration_entities.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/migration_entities.py index 8ee9aadc4e09..b1f847cc83f7 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/migration_entities.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/migration_entities.py @@ -22,6 +22,7 @@ import proto # type: ignore from google.cloud.bigquery_migration_v2.types import ( + assessment_task, migration_error_details, migration_metrics, translation_config, @@ -65,9 +66,11 @@ class MigrationWorkflow(proto.Message): state (google.cloud.bigquery_migration_v2.types.MigrationWorkflow.State): Output only. That status of the workflow. create_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the workflow was created. + Output only. Time when the workflow was + created. last_update_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the workflow was last updated. + Output only. Time when the workflow was last + updated. """ class State(proto.Enum): @@ -142,6 +145,10 @@ class MigrationTask(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + assessment_task_details (google.cloud.bigquery_migration_v2.types.AssessmentTaskDetails): + Task configuration for Assessment. + + This field is a member of `oneof`_ ``task_details``. translation_config_details (google.cloud.bigquery_migration_v2.types.TranslationConfigDetails): Task configuration for CW Batch/Offline SQL Translation. @@ -157,44 +164,52 @@ class MigrationTask(proto.Message): server-generated. type_ (str): The type of the task. This must be one of the supported task - types: Translation_Teradata2BQ, Translation_Redshift2BQ, - Translation_Bteq2BQ, Translation_Oracle2BQ, - Translation_HiveQL2BQ, Translation_SparkSQL2BQ, - Translation_Snowflake2BQ, Translation_Netezza2BQ, - Translation_AzureSynapse2BQ, Translation_Vertica2BQ, - Translation_SQLServer2BQ, Translation_Presto2BQ, - Translation_MySQL2BQ, Translation_Postgresql2BQ, - Translation_SQLite2BQ, Translation_Greenplum2BQ. + types. + + Assessment: + + - ``Assessment_Hive`` - Assessment for Hive. + - ``Assessment_Redshift`` - Assessment for Redshift. + - ``Assessment_Snowflake`` - Assessment for Snowflake. + - ``Assessment_Teradata_v2`` - Assessment for Teradata. + - ``Assessment_Oracle`` - Assessment for Oracle. + - ``Assessment_Hadoop`` - Assessment for Hadoop. + - ``Assessment_Informatica`` - Assessment for Informatica. + + Translation: See `Supported Task + Types `__ + for a list of supported task types. state (google.cloud.bigquery_migration_v2.types.MigrationTask.State): Output only. The current state of the task. processing_error (google.rpc.error_details_pb2.ErrorInfo): Output only. An explanation that may be populated when the task is in FAILED state. create_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the task was created. + Output only. Time when the task was created. last_update_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the task was last updated. + Output only. Time when the task was last + updated. resource_error_details (MutableSequence[google.cloud.bigquery_migration_v2.types.ResourceErrorDetail]): Output only. Provides details to errors and issues encountered while processing the task. Presence of error details does not mean that the task failed. resource_error_count (int): - The number or resources with errors. Note: This is not the - total number of errors as each resource can have more than - one error. This is used to indicate truncation by having a - ``resource_error_count`` that is higher than the size of - ``resource_error_details``. + Output only. The number or resources with errors. Note: This + is not the total number of errors as each resource can have + more than one error. This is used to indicate truncation by + having a ``resource_error_count`` that is higher than the + size of ``resource_error_details``. metrics (MutableSequence[google.cloud.bigquery_migration_v2.types.TimeSeries]): - The metrics for the task. + Output only. The metrics for the task. task_result (google.cloud.bigquery_migration_v2.types.MigrationTaskResult): Output only. The result of the task. total_processing_error_count (int): - Count of all the processing errors in this - task and its subtasks. + Output only. Count of all the processing + errors in this task and its subtasks. total_resource_error_count (int): - Count of all the resource errors in this task - and its subtasks. + Output only. Count of all the resource errors + in this task and its subtasks. """ class State(proto.Enum): @@ -211,7 +226,7 @@ class State(proto.Enum): The task is running, i.e. its subtasks are ready for execution. PAUSED (4): - Tha task is paused. Assigned subtasks can + The task is paused. Assigned subtasks can continue, but no new subtasks will be scheduled. SUCCEEDED (5): The task finished successfully. @@ -227,6 +242,12 @@ class State(proto.Enum): SUCCEEDED = 5 FAILED = 6 + assessment_task_details: assessment_task.AssessmentTaskDetails = proto.Field( + proto.MESSAGE, + number=12, + oneof="task_details", + message=assessment_task.AssessmentTaskDetails, + ) translation_config_details: translation_config.TranslationConfigDetails = ( proto.Field( proto.MESSAGE, @@ -335,17 +356,19 @@ class MigrationSubtask(proto.Message): Presence of error details does not mean that the subtask failed. resource_error_count (int): - The number or resources with errors. Note: This is not the - total number of errors as each resource can have more than - one error. This is used to indicate truncation by having a - ``resource_error_count`` that is higher than the size of - ``resource_error_details``. + Output only. The number or resources with errors. Note: This + is not the total number of errors as each resource can have + more than one error. This is used to indicate truncation by + having a ``resource_error_count`` that is higher than the + size of ``resource_error_details``. create_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the subtask was created. + Output only. Time when the subtask was + created. last_update_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the subtask was last updated. + Output only. Time when the subtask was last + updated. metrics (MutableSequence[google.cloud.bigquery_migration_v2.types.TimeSeries]): - The metrics for the subtask. + Output only. The metrics for the subtask. """ class State(proto.Enum): @@ -461,6 +484,9 @@ class TranslationTaskResult(proto.Message): report_log_messages (MutableSequence[google.cloud.bigquery_migration_v2.types.GcsReportLogMessage]): The records from the aggregate CSV report for a migration workflow. + console_uri (str): + The Cloud Console URI for the migration + workflow. """ translated_literals: MutableSequence[gcbm_translation_details.Literal] = ( @@ -477,6 +503,10 @@ class TranslationTaskResult(proto.Message): message=translation_usability.GcsReportLogMessage, ) ) + console_uri: str = proto.Field( + proto.STRING, + number=3, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/translation_details.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/translation_details.py index f876854398c1..288d336757ab 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/translation_details.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/types/translation_details.py @@ -23,6 +23,8 @@ package="google.cloud.bigquery.migration.v2", manifest={ "TranslationDetails", + "SuggestionConfig", + "SuggestionStep", "SourceTargetMapping", "SourceSpec", "TargetSpec", @@ -56,6 +58,9 @@ class TranslationDetails(proto.Message): set of targets will be generated. Some additional target types may be slower to generate. See the documentation for the set of available target types. + suggestion_config (google.cloud.bigquery_migration_v2.types.SuggestionConfig): + The configuration for the suggestion if + requested as a target type. """ source_target_mapping: MutableSequence["SourceTargetMapping"] = proto.RepeatedField( @@ -80,6 +85,81 @@ class TranslationDetails(proto.Message): proto.STRING, number=5, ) + suggestion_config: "SuggestionConfig" = proto.Field( + proto.MESSAGE, + number=6, + message="SuggestionConfig", + ) + + +class SuggestionConfig(proto.Message): + r"""The configuration for the suggestion if requested as a target + type. + + Attributes: + skip_suggestion_steps (MutableSequence[google.cloud.bigquery_migration_v2.types.SuggestionStep]): + The list of suggestion steps to skip. + """ + + skip_suggestion_steps: MutableSequence["SuggestionStep"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SuggestionStep", + ) + + +class SuggestionStep(proto.Message): + r"""Suggestion step to skip. + + Attributes: + suggestion_type (google.cloud.bigquery_migration_v2.types.SuggestionStep.SuggestionType): + The type of suggestion. + rewrite_target (google.cloud.bigquery_migration_v2.types.SuggestionStep.RewriteTarget): + The rewrite target. + """ + + class SuggestionType(proto.Enum): + r"""Suggestion type. + + Values: + SUGGESTION_TYPE_UNSPECIFIED (0): + Suggestion type unspecified. + QUERY_CUSTOMIZATION (1): + Query customization. + TRANSLATION_EXPLANATION (2): + Translation explanation. + """ + + SUGGESTION_TYPE_UNSPECIFIED = 0 + QUERY_CUSTOMIZATION = 1 + TRANSLATION_EXPLANATION = 2 + + class RewriteTarget(proto.Enum): + r"""The target to apply the suggestion to. + + Values: + REWRITE_TARGET_UNSPECIFIED (0): + Rewrite target unspecified. + SOURCE_SQL (1): + Source SQL. + TARGET_SQL (2): + Target SQL. + """ + + REWRITE_TARGET_UNSPECIFIED = 0 + SOURCE_SQL = 1 + TARGET_SQL = 2 + + suggestion_type: SuggestionType = proto.Field( + proto.ENUM, + number=1, + enum=SuggestionType, + ) + rewrite_target: RewriteTarget = proto.Field( + proto.ENUM, + number=2, + enum=RewriteTarget, + ) class SourceTargetMapping(proto.Message): @@ -123,6 +203,11 @@ class SourceSpec(proto.Message): literal (google.cloud.bigquery_migration_v2.types.Literal): Source literal. + This field is a member of `oneof`_ ``source``. + gcs_file_path (str): + The path to a single source file in Cloud + Storage. + This field is a member of `oneof`_ ``source``. encoding (str): Optional. The optional field to specify the @@ -140,6 +225,11 @@ class SourceSpec(proto.Message): oneof="source", message="Literal", ) + gcs_file_path: str = proto.Field( + proto.STRING, + number=4, + oneof="source", + ) encoding: str = proto.Field( proto.STRING, number=3, diff --git a/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2/test_migration_service.py b/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2/test_migration_service.py index 65ce975f9a4e..d0b937eadabe 100644 --- a/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2/test_migration_service.py +++ b/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2/test_migration_service.py @@ -61,6 +61,7 @@ transports, ) from google.cloud.bigquery_migration_v2.types import ( + assessment_task, migration_entities, migration_error_details, migration_metrics, diff --git a/packages/google-cloud-bigquery/docs/README.rst b/packages/google-cloud-bigquery/docs/README.rst index 23ed9257ddc4..705ef5ce712c 100644 --- a/packages/google-cloud-bigquery/docs/README.rst +++ b/packages/google-cloud-bigquery/docs/README.rst @@ -52,11 +52,11 @@ dependencies. Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Python >= 3.9 +Python >= 3.10 Unsupported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Python == 2.7, Python == 3.5, Python == 3.6, Python == 3.7, and Python == 3.8. +Python <= 3.9. The last version of this library compatible with Python 2.7 and 3.5 is `google-cloud-bigquery==1.28.0`. diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py index 2842bb4a6e27..ad9ee94e51c4 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py @@ -129637,6 +129637,10 @@ class ConsumeReservationType(proto.Enum): set. ANY_RESERVATION (200008121): Consume any allocation available. + ANY_RESERVATION_THEN_FAIL (236541178): + Consume any reservation available, but fail + if no reservation is available. Will not consume + from the on-demand pool. NO_RESERVATION (169322030): Do not consume from any allocated capacity. SPECIFIC_RESERVATION (229889055): @@ -129661,6 +129665,7 @@ class ConsumeReservationType(proto.Enum): UNDEFINED_CONSUME_RESERVATION_TYPE = 0 ANY_RESERVATION = 200008121 + ANY_RESERVATION_THEN_FAIL = 236541178 NO_RESERVATION = 169322030 SPECIFIC_RESERVATION = 229889055 SPECIFIC_THEN_ANY_RESERVATION = 37025924 diff --git a/packages/google-cloud-compute/docs/compute_v1/global_vm_extension_policies.rst b/packages/google-cloud-compute/docs/compute_v1/global_vm_extension_policies.rst new file mode 100644 index 000000000000..ecae942b2adf --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/global_vm_extension_policies.rst @@ -0,0 +1,10 @@ +GlobalVmExtensionPolicies +------------------------------------------- + +.. automodule:: google.cloud.compute_v1.services.global_vm_extension_policies + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.global_vm_extension_policies.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/rollout_plans.rst b/packages/google-cloud-compute/docs/compute_v1/rollout_plans.rst new file mode 100644 index 000000000000..08f6918ad8d2 --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/rollout_plans.rst @@ -0,0 +1,10 @@ +RolloutPlans +------------------------------ + +.. automodule:: google.cloud.compute_v1.services.rollout_plans + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.rollout_plans.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/rollouts.rst b/packages/google-cloud-compute/docs/compute_v1/rollouts.rst new file mode 100644 index 000000000000..4e22f8e66420 --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/rollouts.rst @@ -0,0 +1,10 @@ +Rollouts +-------------------------- + +.. automodule:: google.cloud.compute_v1.services.rollouts + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.rollouts.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/services_.rst b/packages/google-cloud-compute/docs/compute_v1/services_.rst index 099c91825ded..b74aeb2f975c 100644 --- a/packages/google-cloud-compute/docs/compute_v1/services_.rst +++ b/packages/google-cloud-compute/docs/compute_v1/services_.rst @@ -23,6 +23,7 @@ Services for Google Cloud Compute v1 API global_operations global_organization_operations global_public_delegated_prefixes + global_vm_extension_policies health_checks image_family_views images @@ -97,6 +98,8 @@ Services for Google Cloud Compute v1 API reservation_slots reservation_sub_blocks resource_policies + rollout_plans + rollouts routers routes security_policies diff --git a/packages/google-cloud-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index 8da51c87f40d..95463f674400 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -64,6 +64,9 @@ from google.cloud.compute_v1.services.global_public_delegated_prefixes.client import ( GlobalPublicDelegatedPrefixesClient, ) +from google.cloud.compute_v1.services.global_vm_extension_policies.client import ( + GlobalVmExtensionPoliciesClient, +) from google.cloud.compute_v1.services.health_checks.client import HealthChecksClient from google.cloud.compute_v1.services.image_family_views.client import ( ImageFamilyViewsClient, @@ -248,6 +251,8 @@ from google.cloud.compute_v1.services.resource_policies.client import ( ResourcePoliciesClient, ) +from google.cloud.compute_v1.services.rollout_plans.client import RolloutPlansClient +from google.cloud.compute_v1.services.rollouts.client import RolloutsClient from google.cloud.compute_v1.services.routers.client import RoutersClient from google.cloud.compute_v1.services.routes.client import RoutesClient from google.cloud.compute_v1.services.security_policies.client import ( @@ -351,6 +356,7 @@ AggregatedListForwardingRulesRequest, AggregatedListFutureReservationsRequest, AggregatedListGlobalOperationsRequest, + AggregatedListGlobalVmExtensionPoliciesRequest, AggregatedListHealthChecksRequest, AggregatedListInstanceGroupManagersRequest, AggregatedListInstanceGroupsRequest, @@ -503,6 +509,8 @@ CancelFutureReservationRequest, CancelInstanceGroupManagerResizeRequestRequest, CancelRegionInstanceGroupManagerResizeRequestRequest, + CancelRequestRemovePeeringNetworkRequest, + CancelRolloutRequest, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -558,6 +566,7 @@ DeleteGlobalOrganizationOperationRequest, DeleteGlobalOrganizationOperationResponse, DeleteGlobalPublicDelegatedPrefixeRequest, + DeleteGlobalVmExtensionPolicyRequest, DeleteHealthCheckRequest, DeleteImageRequest, DeleteInstanceGroupManagerRequest, @@ -619,6 +628,8 @@ DeleteRegionUrlMapRequest, DeleteReservationRequest, DeleteResourcePolicyRequest, + DeleteRolloutPlanRequest, + DeleteRolloutRequest, DeleteRoutePolicyRouterRequest, DeleteRouteRequest, DeleteRouterRequest, @@ -768,6 +779,7 @@ GetGlobalOperationRequest, GetGlobalOrganizationOperationRequest, GetGlobalPublicDelegatedPrefixeRequest, + GetGlobalVmExtensionPolicyRequest, GetGuestAttributesInstanceRequest, GetHealthBackendServiceRequest, GetHealthCheckRequest, @@ -786,6 +798,7 @@ GetIamPolicyInstantSnapshotRequest, GetIamPolicyInterconnectAttachmentGroupRequest, GetIamPolicyInterconnectGroupRequest, + GetIamPolicyLicenseCodeRequest, GetIamPolicyLicenseRequest, GetIamPolicyMachineImageRequest, GetIamPolicyNetworkAttachmentRequest, @@ -884,6 +897,8 @@ GetReservationSlotRequest, GetReservationSubBlockRequest, GetResourcePolicyRequest, + GetRolloutPlanRequest, + GetRolloutRequest, GetRoutePolicyRouterRequest, GetRouteRequest, GetRouterRequest, @@ -934,6 +949,16 @@ GlobalOrganizationSetPolicyRequest, GlobalSetLabelsRequest, GlobalSetPolicyRequest, + GlobalVmExtensionPolicy, + GlobalVmExtensionPolicyExtensionPolicy, + GlobalVmExtensionPolicyInstanceSelector, + GlobalVmExtensionPolicyLabelSelector, + GlobalVmExtensionPolicyList, + GlobalVmExtensionPolicyRolloutOperation, + GlobalVmExtensionPolicyRolloutOperationRolloutInput, + GlobalVmExtensionPolicyRolloutOperationRolloutStatus, + GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata, + GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus, GroupMaintenanceInfo, GRPCHealthCheck, GRPCTLSHealthCheck, @@ -1003,6 +1028,7 @@ InsertGlobalForwardingRuleRequest, InsertGlobalNetworkEndpointGroupRequest, InsertGlobalPublicDelegatedPrefixeRequest, + InsertGlobalVmExtensionPolicyRequest, InsertHealthCheckRequest, InsertImageRequest, InsertInstanceGroupManagerRequest, @@ -1057,6 +1083,7 @@ InsertRegionUrlMapRequest, InsertReservationRequest, InsertResourcePolicyRequest, + InsertRolloutPlanRequest, InsertRouteRequest, InsertRouterRequest, InsertSecurityPolicyRequest, @@ -1295,6 +1322,7 @@ ListGlobalOperationsRequest, ListGlobalOrganizationOperationsRequest, ListGlobalPublicDelegatedPrefixesRequest, + ListGlobalVmExtensionPoliciesRequest, ListHealthChecksRequest, ListImagesRequest, ListInstanceGroupManagerResizeRequestsRequest, @@ -1377,6 +1405,8 @@ ListReservationsRequest, ListReservationSubBlocksRequest, ListResourcePoliciesRequest, + ListRolloutPlansRequest, + ListRolloutsRequest, ListRoutePoliciesRoutersRequest, ListRoutersRequest, ListRoutesRequest, @@ -1481,6 +1511,7 @@ NetworkProfilesListResponse, NetworkRoutingConfig, NetworksAddPeeringRequest, + NetworksCancelRequestRemovePeeringRequest, NetworksGetEffectiveFirewallsResponse, NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy, NetworksRemovePeeringRequest, @@ -1766,6 +1797,23 @@ ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, ResumeInstancesRegionInstanceGroupManagerRequest, + Rollout, + RolloutPlan, + RolloutPlansListResponse, + RolloutPlanWave, + RolloutPlanWaveOrchestrationOptions, + RolloutPlanWaveOrchestrationOptionsDelay, + RolloutPlanWaveSelector, + RolloutPlanWaveSelectorLocationSelector, + RolloutPlanWaveSelectorResourceHierarchySelector, + RolloutPlanWaveValidation, + RolloutPlanWaveValidationTimeBasedValidationMetadata, + RolloutRolloutEntity, + RolloutRolloutEntityOrchestratedEntity, + RolloutsListResponse, + RolloutWaveDetails, + RolloutWaveDetailsOrchestratedWaveDetails, + RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus, Route, RouteAsPath, RouteList, @@ -1876,6 +1924,7 @@ SetIamPolicyInstantSnapshotRequest, SetIamPolicyInterconnectAttachmentGroupRequest, SetIamPolicyInterconnectGroupRequest, + SetIamPolicyLicenseCodeRequest, SetIamPolicyLicenseRequest, SetIamPolicyMachineImageRequest, SetIamPolicyNetworkAttachmentRequest, @@ -2155,6 +2204,7 @@ UpdateDisplayDeviceInstanceRequest, UpdateFirewallRequest, UpdateFutureReservationRequest, + UpdateGlobalVmExtensionPolicyRequest, UpdateHealthCheckRequest, UpdateInstanceRequest, UpdateKmsKeyDiskRequest, @@ -2202,7 +2252,9 @@ VmEndpointNatMappingsInterfaceNatMappings, VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings, VmEndpointNatMappingsList, + VmExtensionPoliciesScopedList, VmExtensionPolicy, + VmExtensionPolicyAggregatedListResponse, VmExtensionPolicyExtensionPolicy, VmExtensionPolicyInstanceSelector, VmExtensionPolicyLabelSelector, @@ -2276,6 +2328,7 @@ "GlobalOperationsClient", "GlobalOrganizationOperationsClient", "GlobalPublicDelegatedPrefixesClient", + "GlobalVmExtensionPoliciesClient", "HealthChecksClient", "ImageFamilyViewsClient", "ImagesClient", @@ -2350,6 +2403,8 @@ "ReservationSlotsClient", "ReservationSubBlocksClient", "ResourcePoliciesClient", + "RolloutPlansClient", + "RolloutsClient", "RoutersClient", "RoutesClient", "SecurityPoliciesClient", @@ -2426,6 +2481,7 @@ "AggregatedListForwardingRulesRequest", "AggregatedListFutureReservationsRequest", "AggregatedListGlobalOperationsRequest", + "AggregatedListGlobalVmExtensionPoliciesRequest", "AggregatedListHealthChecksRequest", "AggregatedListInstanceGroupManagersRequest", "AggregatedListInstanceGroupsRequest", @@ -2578,6 +2634,8 @@ "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", "CancelRegionInstanceGroupManagerResizeRequestRequest", + "CancelRequestRemovePeeringNetworkRequest", + "CancelRolloutRequest", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -2633,6 +2691,7 @@ "DeleteGlobalOrganizationOperationRequest", "DeleteGlobalOrganizationOperationResponse", "DeleteGlobalPublicDelegatedPrefixeRequest", + "DeleteGlobalVmExtensionPolicyRequest", "DeleteHealthCheckRequest", "DeleteImageRequest", "DeleteInstanceGroupManagerRequest", @@ -2694,6 +2753,8 @@ "DeleteRegionUrlMapRequest", "DeleteReservationRequest", "DeleteResourcePolicyRequest", + "DeleteRolloutPlanRequest", + "DeleteRolloutRequest", "DeleteRoutePolicyRouterRequest", "DeleteRouteRequest", "DeleteRouterRequest", @@ -2843,6 +2904,7 @@ "GetGlobalOperationRequest", "GetGlobalOrganizationOperationRequest", "GetGlobalPublicDelegatedPrefixeRequest", + "GetGlobalVmExtensionPolicyRequest", "GetGuestAttributesInstanceRequest", "GetHealthBackendServiceRequest", "GetHealthCheckRequest", @@ -2861,6 +2923,7 @@ "GetIamPolicyInstantSnapshotRequest", "GetIamPolicyInterconnectAttachmentGroupRequest", "GetIamPolicyInterconnectGroupRequest", + "GetIamPolicyLicenseCodeRequest", "GetIamPolicyLicenseRequest", "GetIamPolicyMachineImageRequest", "GetIamPolicyNetworkAttachmentRequest", @@ -2959,6 +3022,8 @@ "GetReservationSlotRequest", "GetReservationSubBlockRequest", "GetResourcePolicyRequest", + "GetRolloutPlanRequest", + "GetRolloutRequest", "GetRoutePolicyRouterRequest", "GetRouteRequest", "GetRouterRequest", @@ -3009,6 +3074,16 @@ "GlobalOrganizationSetPolicyRequest", "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", + "GlobalVmExtensionPolicy", + "GlobalVmExtensionPolicyExtensionPolicy", + "GlobalVmExtensionPolicyInstanceSelector", + "GlobalVmExtensionPolicyLabelSelector", + "GlobalVmExtensionPolicyList", + "GlobalVmExtensionPolicyRolloutOperation", + "GlobalVmExtensionPolicyRolloutOperationRolloutInput", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatus", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus", "GroupMaintenanceInfo", "GRPCHealthCheck", "GRPCTLSHealthCheck", @@ -3078,6 +3153,7 @@ "InsertGlobalForwardingRuleRequest", "InsertGlobalNetworkEndpointGroupRequest", "InsertGlobalPublicDelegatedPrefixeRequest", + "InsertGlobalVmExtensionPolicyRequest", "InsertHealthCheckRequest", "InsertImageRequest", "InsertInstanceGroupManagerRequest", @@ -3132,6 +3208,7 @@ "InsertRegionUrlMapRequest", "InsertReservationRequest", "InsertResourcePolicyRequest", + "InsertRolloutPlanRequest", "InsertRouteRequest", "InsertRouterRequest", "InsertSecurityPolicyRequest", @@ -3370,6 +3447,7 @@ "ListGlobalOperationsRequest", "ListGlobalOrganizationOperationsRequest", "ListGlobalPublicDelegatedPrefixesRequest", + "ListGlobalVmExtensionPoliciesRequest", "ListHealthChecksRequest", "ListImagesRequest", "ListInstanceGroupManagerResizeRequestsRequest", @@ -3452,6 +3530,8 @@ "ListReservationsRequest", "ListReservationSubBlocksRequest", "ListResourcePoliciesRequest", + "ListRolloutPlansRequest", + "ListRolloutsRequest", "ListRoutePoliciesRoutersRequest", "ListRoutersRequest", "ListRoutesRequest", @@ -3556,6 +3636,7 @@ "NetworkProfilesListResponse", "NetworkRoutingConfig", "NetworksAddPeeringRequest", + "NetworksCancelRequestRemovePeeringRequest", "NetworksGetEffectiveFirewallsResponse", "NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "NetworksRemovePeeringRequest", @@ -3841,6 +3922,23 @@ "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "Rollout", + "RolloutPlan", + "RolloutPlansListResponse", + "RolloutPlanWave", + "RolloutPlanWaveOrchestrationOptions", + "RolloutPlanWaveOrchestrationOptionsDelay", + "RolloutPlanWaveSelector", + "RolloutPlanWaveSelectorLocationSelector", + "RolloutPlanWaveSelectorResourceHierarchySelector", + "RolloutPlanWaveValidation", + "RolloutPlanWaveValidationTimeBasedValidationMetadata", + "RolloutRolloutEntity", + "RolloutRolloutEntityOrchestratedEntity", + "RolloutsListResponse", + "RolloutWaveDetails", + "RolloutWaveDetailsOrchestratedWaveDetails", + "RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus", "Route", "RouteAsPath", "RouteList", @@ -3951,6 +4049,7 @@ "SetIamPolicyInstantSnapshotRequest", "SetIamPolicyInterconnectAttachmentGroupRequest", "SetIamPolicyInterconnectGroupRequest", + "SetIamPolicyLicenseCodeRequest", "SetIamPolicyLicenseRequest", "SetIamPolicyMachineImageRequest", "SetIamPolicyNetworkAttachmentRequest", @@ -4230,6 +4329,7 @@ "UpdateDisplayDeviceInstanceRequest", "UpdateFirewallRequest", "UpdateFutureReservationRequest", + "UpdateGlobalVmExtensionPolicyRequest", "UpdateHealthCheckRequest", "UpdateInstanceRequest", "UpdateKmsKeyDiskRequest", @@ -4277,7 +4377,9 @@ "VmEndpointNatMappingsInterfaceNatMappings", "VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings", "VmEndpointNatMappingsList", + "VmExtensionPoliciesScopedList", "VmExtensionPolicy", + "VmExtensionPolicyAggregatedListResponse", "VmExtensionPolicyExtensionPolicy", "VmExtensionPolicyInstanceSelector", "VmExtensionPolicyLabelSelector", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 94ea3b616380..79e76a65d034 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -45,6 +45,7 @@ from .services.global_public_delegated_prefixes import ( GlobalPublicDelegatedPrefixesClient, ) +from .services.global_vm_extension_policies import GlobalVmExtensionPoliciesClient from .services.health_checks import HealthChecksClient from .services.image_family_views import ImageFamilyViewsClient from .services.images import ImagesClient @@ -127,6 +128,8 @@ from .services.reservation_sub_blocks import ReservationSubBlocksClient from .services.reservations import ReservationsClient from .services.resource_policies import ResourcePoliciesClient +from .services.rollout_plans import RolloutPlansClient +from .services.rollouts import RolloutsClient from .services.routers import RoutersClient from .services.routes import RoutesClient from .services.security_policies import SecurityPoliciesClient @@ -204,6 +207,7 @@ AggregatedListForwardingRulesRequest, AggregatedListFutureReservationsRequest, AggregatedListGlobalOperationsRequest, + AggregatedListGlobalVmExtensionPoliciesRequest, AggregatedListHealthChecksRequest, AggregatedListInstanceGroupManagersRequest, AggregatedListInstanceGroupsRequest, @@ -356,6 +360,8 @@ CancelFutureReservationRequest, CancelInstanceGroupManagerResizeRequestRequest, CancelRegionInstanceGroupManagerResizeRequestRequest, + CancelRequestRemovePeeringNetworkRequest, + CancelRolloutRequest, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -411,6 +417,7 @@ DeleteGlobalOrganizationOperationRequest, DeleteGlobalOrganizationOperationResponse, DeleteGlobalPublicDelegatedPrefixeRequest, + DeleteGlobalVmExtensionPolicyRequest, DeleteHealthCheckRequest, DeleteImageRequest, DeleteInstanceGroupManagerRequest, @@ -472,6 +479,8 @@ DeleteRegionUrlMapRequest, DeleteReservationRequest, DeleteResourcePolicyRequest, + DeleteRolloutPlanRequest, + DeleteRolloutRequest, DeleteRoutePolicyRouterRequest, DeleteRouteRequest, DeleteRouterRequest, @@ -621,6 +630,7 @@ GetGlobalOperationRequest, GetGlobalOrganizationOperationRequest, GetGlobalPublicDelegatedPrefixeRequest, + GetGlobalVmExtensionPolicyRequest, GetGuestAttributesInstanceRequest, GetHealthBackendServiceRequest, GetHealthCheckRequest, @@ -639,6 +649,7 @@ GetIamPolicyInstantSnapshotRequest, GetIamPolicyInterconnectAttachmentGroupRequest, GetIamPolicyInterconnectGroupRequest, + GetIamPolicyLicenseCodeRequest, GetIamPolicyLicenseRequest, GetIamPolicyMachineImageRequest, GetIamPolicyNetworkAttachmentRequest, @@ -737,6 +748,8 @@ GetReservationSlotRequest, GetReservationSubBlockRequest, GetResourcePolicyRequest, + GetRolloutPlanRequest, + GetRolloutRequest, GetRoutePolicyRouterRequest, GetRouteRequest, GetRouterRequest, @@ -787,6 +800,16 @@ GlobalOrganizationSetPolicyRequest, GlobalSetLabelsRequest, GlobalSetPolicyRequest, + GlobalVmExtensionPolicy, + GlobalVmExtensionPolicyExtensionPolicy, + GlobalVmExtensionPolicyInstanceSelector, + GlobalVmExtensionPolicyLabelSelector, + GlobalVmExtensionPolicyList, + GlobalVmExtensionPolicyRolloutOperation, + GlobalVmExtensionPolicyRolloutOperationRolloutInput, + GlobalVmExtensionPolicyRolloutOperationRolloutStatus, + GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata, + GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus, GroupMaintenanceInfo, GRPCHealthCheck, GRPCTLSHealthCheck, @@ -856,6 +879,7 @@ InsertGlobalForwardingRuleRequest, InsertGlobalNetworkEndpointGroupRequest, InsertGlobalPublicDelegatedPrefixeRequest, + InsertGlobalVmExtensionPolicyRequest, InsertHealthCheckRequest, InsertImageRequest, InsertInstanceGroupManagerRequest, @@ -910,6 +934,7 @@ InsertRegionUrlMapRequest, InsertReservationRequest, InsertResourcePolicyRequest, + InsertRolloutPlanRequest, InsertRouteRequest, InsertRouterRequest, InsertSecurityPolicyRequest, @@ -1148,6 +1173,7 @@ ListGlobalOperationsRequest, ListGlobalOrganizationOperationsRequest, ListGlobalPublicDelegatedPrefixesRequest, + ListGlobalVmExtensionPoliciesRequest, ListHealthChecksRequest, ListImagesRequest, ListInstanceGroupManagerResizeRequestsRequest, @@ -1230,6 +1256,8 @@ ListReservationsRequest, ListReservationSubBlocksRequest, ListResourcePoliciesRequest, + ListRolloutPlansRequest, + ListRolloutsRequest, ListRoutePoliciesRoutersRequest, ListRoutersRequest, ListRoutesRequest, @@ -1334,6 +1362,7 @@ NetworkProfilesListResponse, NetworkRoutingConfig, NetworksAddPeeringRequest, + NetworksCancelRequestRemovePeeringRequest, NetworksGetEffectiveFirewallsResponse, NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy, NetworksRemovePeeringRequest, @@ -1619,6 +1648,23 @@ ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, ResumeInstancesRegionInstanceGroupManagerRequest, + Rollout, + RolloutPlan, + RolloutPlansListResponse, + RolloutPlanWave, + RolloutPlanWaveOrchestrationOptions, + RolloutPlanWaveOrchestrationOptionsDelay, + RolloutPlanWaveSelector, + RolloutPlanWaveSelectorLocationSelector, + RolloutPlanWaveSelectorResourceHierarchySelector, + RolloutPlanWaveValidation, + RolloutPlanWaveValidationTimeBasedValidationMetadata, + RolloutRolloutEntity, + RolloutRolloutEntityOrchestratedEntity, + RolloutsListResponse, + RolloutWaveDetails, + RolloutWaveDetailsOrchestratedWaveDetails, + RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus, Route, RouteAsPath, RouteList, @@ -1729,6 +1775,7 @@ SetIamPolicyInstantSnapshotRequest, SetIamPolicyInterconnectAttachmentGroupRequest, SetIamPolicyInterconnectGroupRequest, + SetIamPolicyLicenseCodeRequest, SetIamPolicyLicenseRequest, SetIamPolicyMachineImageRequest, SetIamPolicyNetworkAttachmentRequest, @@ -2008,6 +2055,7 @@ UpdateDisplayDeviceInstanceRequest, UpdateFirewallRequest, UpdateFutureReservationRequest, + UpdateGlobalVmExtensionPolicyRequest, UpdateHealthCheckRequest, UpdateInstanceRequest, UpdateKmsKeyDiskRequest, @@ -2055,7 +2103,9 @@ VmEndpointNatMappingsInterfaceNatMappings, VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings, VmEndpointNatMappingsList, + VmExtensionPoliciesScopedList, VmExtensionPolicy, + VmExtensionPolicyAggregatedListResponse, VmExtensionPolicyExtensionPolicy, VmExtensionPolicyInstanceSelector, VmExtensionPolicyLabelSelector, @@ -2246,6 +2296,7 @@ def _get_version(dependency_name): "AggregatedListForwardingRulesRequest", "AggregatedListFutureReservationsRequest", "AggregatedListGlobalOperationsRequest", + "AggregatedListGlobalVmExtensionPoliciesRequest", "AggregatedListHealthChecksRequest", "AggregatedListInstanceGroupManagersRequest", "AggregatedListInstanceGroupsRequest", @@ -2400,6 +2451,8 @@ def _get_version(dependency_name): "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", "CancelRegionInstanceGroupManagerResizeRequestRequest", + "CancelRequestRemovePeeringNetworkRequest", + "CancelRolloutRequest", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -2456,6 +2509,7 @@ def _get_version(dependency_name): "DeleteGlobalOrganizationOperationRequest", "DeleteGlobalOrganizationOperationResponse", "DeleteGlobalPublicDelegatedPrefixeRequest", + "DeleteGlobalVmExtensionPolicyRequest", "DeleteHealthCheckRequest", "DeleteImageRequest", "DeleteInstanceGroupManagerRequest", @@ -2517,6 +2571,8 @@ def _get_version(dependency_name): "DeleteRegionUrlMapRequest", "DeleteReservationRequest", "DeleteResourcePolicyRequest", + "DeleteRolloutPlanRequest", + "DeleteRolloutRequest", "DeleteRoutePolicyRouterRequest", "DeleteRouteRequest", "DeleteRouterRequest", @@ -2675,6 +2731,7 @@ def _get_version(dependency_name): "GetGlobalOperationRequest", "GetGlobalOrganizationOperationRequest", "GetGlobalPublicDelegatedPrefixeRequest", + "GetGlobalVmExtensionPolicyRequest", "GetGuestAttributesInstanceRequest", "GetHealthBackendServiceRequest", "GetHealthCheckRequest", @@ -2693,6 +2750,7 @@ def _get_version(dependency_name): "GetIamPolicyInstantSnapshotRequest", "GetIamPolicyInterconnectAttachmentGroupRequest", "GetIamPolicyInterconnectGroupRequest", + "GetIamPolicyLicenseCodeRequest", "GetIamPolicyLicenseRequest", "GetIamPolicyMachineImageRequest", "GetIamPolicyNetworkAttachmentRequest", @@ -2791,6 +2849,8 @@ def _get_version(dependency_name): "GetReservationSlotRequest", "GetReservationSubBlockRequest", "GetResourcePolicyRequest", + "GetRolloutPlanRequest", + "GetRolloutRequest", "GetRoutePolicyRouterRequest", "GetRouteRequest", "GetRouterRequest", @@ -2847,6 +2907,17 @@ def _get_version(dependency_name): "GlobalPublicDelegatedPrefixesClient", "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", + "GlobalVmExtensionPoliciesClient", + "GlobalVmExtensionPolicy", + "GlobalVmExtensionPolicyExtensionPolicy", + "GlobalVmExtensionPolicyInstanceSelector", + "GlobalVmExtensionPolicyLabelSelector", + "GlobalVmExtensionPolicyList", + "GlobalVmExtensionPolicyRolloutOperation", + "GlobalVmExtensionPolicyRolloutOperationRolloutInput", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatus", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus", "GroupMaintenanceInfo", "GuestAttributes", "GuestAttributesEntry", @@ -2917,6 +2988,7 @@ def _get_version(dependency_name): "InsertGlobalForwardingRuleRequest", "InsertGlobalNetworkEndpointGroupRequest", "InsertGlobalPublicDelegatedPrefixeRequest", + "InsertGlobalVmExtensionPolicyRequest", "InsertHealthCheckRequest", "InsertImageRequest", "InsertInstanceGroupManagerRequest", @@ -2971,6 +3043,7 @@ def _get_version(dependency_name): "InsertRegionUrlMapRequest", "InsertReservationRequest", "InsertResourcePolicyRequest", + "InsertRolloutPlanRequest", "InsertRouteRequest", "InsertRouterRequest", "InsertSecurityPolicyRequest", @@ -3225,6 +3298,7 @@ def _get_version(dependency_name): "ListGlobalOperationsRequest", "ListGlobalOrganizationOperationsRequest", "ListGlobalPublicDelegatedPrefixesRequest", + "ListGlobalVmExtensionPoliciesRequest", "ListHealthChecksRequest", "ListImagesRequest", "ListInstanceGroupManagerResizeRequestsRequest", @@ -3307,6 +3381,8 @@ def _get_version(dependency_name): "ListReservationSubBlocksRequest", "ListReservationsRequest", "ListResourcePoliciesRequest", + "ListRolloutPlansRequest", + "ListRolloutsRequest", "ListRoutePoliciesRoutersRequest", "ListRoutersRequest", "ListRoutesRequest", @@ -3418,6 +3494,7 @@ def _get_version(dependency_name): "NetworkProfilesListResponse", "NetworkRoutingConfig", "NetworksAddPeeringRequest", + "NetworksCancelRequestRemovePeeringRequest", "NetworksClient", "NetworksGetEffectiveFirewallsResponse", "NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", @@ -3751,6 +3828,25 @@ def _get_version(dependency_name): "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "Rollout", + "RolloutPlan", + "RolloutPlanWave", + "RolloutPlanWaveOrchestrationOptions", + "RolloutPlanWaveOrchestrationOptionsDelay", + "RolloutPlanWaveSelector", + "RolloutPlanWaveSelectorLocationSelector", + "RolloutPlanWaveSelectorResourceHierarchySelector", + "RolloutPlanWaveValidation", + "RolloutPlanWaveValidationTimeBasedValidationMetadata", + "RolloutPlansClient", + "RolloutPlansListResponse", + "RolloutRolloutEntity", + "RolloutRolloutEntityOrchestratedEntity", + "RolloutWaveDetails", + "RolloutWaveDetailsOrchestratedWaveDetails", + "RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus", + "RolloutsClient", + "RolloutsListResponse", "Route", "RouteAsPath", "RouteList", @@ -3866,6 +3962,7 @@ def _get_version(dependency_name): "SetIamPolicyInstantSnapshotRequest", "SetIamPolicyInterconnectAttachmentGroupRequest", "SetIamPolicyInterconnectGroupRequest", + "SetIamPolicyLicenseCodeRequest", "SetIamPolicyLicenseRequest", "SetIamPolicyMachineImageRequest", "SetIamPolicyNetworkAttachmentRequest", @@ -4159,6 +4256,7 @@ def _get_version(dependency_name): "UpdateDisplayDeviceInstanceRequest", "UpdateFirewallRequest", "UpdateFutureReservationRequest", + "UpdateGlobalVmExtensionPolicyRequest", "UpdateHealthCheckRequest", "UpdateInstanceRequest", "UpdateKmsKeyDiskRequest", @@ -4207,7 +4305,9 @@ def _get_version(dependency_name): "VmEndpointNatMappingsInterfaceNatMappings", "VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings", "VmEndpointNatMappingsList", + "VmExtensionPoliciesScopedList", "VmExtensionPolicy", + "VmExtensionPolicyAggregatedListResponse", "VmExtensionPolicyExtensionPolicy", "VmExtensionPolicyInstanceSelector", "VmExtensionPolicyLabelSelector", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json index 1364eae6590d..d6534f4cabf1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json +++ b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json @@ -980,6 +980,45 @@ } } }, + "GlobalVmExtensionPolicies": { + "clients": { + "rest": { + "libraryClient": "GlobalVmExtensionPoliciesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, "HealthChecks": { "clients": { "rest": { @@ -2013,6 +2052,16 @@ "get" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "TestIamPermissions": { "methods": [ "test_iam_permissions" @@ -2429,6 +2478,11 @@ "add_peering" ] }, + "CancelRequestRemovePeering": { + "methods": [ + "cancel_request_remove_peering" + ] + }, "Delete": { "methods": [ "delete" @@ -4676,6 +4730,64 @@ } } }, + "RolloutPlans": { + "clients": { + "rest": { + "libraryClient": "RolloutPlansClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "Rollouts": { + "clients": { + "rest": { + "libraryClient": "RolloutsClient", + "rpcs": { + "Cancel": { + "methods": [ + "cancel" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, "Routers": { "clients": { "rest": { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/__init__.py new file mode 100644 index 000000000000..ce70a577c0b6 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import GlobalVmExtensionPoliciesClient + +__all__ = ("GlobalVmExtensionPoliciesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/client.py new file mode 100644 index 000000000000..b4bac1c56dae --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/client.py @@ -0,0 +1,2015 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import functools +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation, gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.extended_operation as extended_operation # type: ignore + +from google.cloud.compute_v1.services.global_vm_extension_policies import pagers +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, GlobalVmExtensionPoliciesTransport +from .transports.rest import GlobalVmExtensionPoliciesRestTransport + + +class GlobalVmExtensionPoliciesClientMeta(type): + """Metaclass for the GlobalVmExtensionPolicies client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[GlobalVmExtensionPoliciesTransport]] + _transport_registry["rest"] = GlobalVmExtensionPoliciesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[GlobalVmExtensionPoliciesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class GlobalVmExtensionPoliciesClient(metaclass=GlobalVmExtensionPoliciesClientMeta): + """The GlobalVmExtensionPolicies API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GlobalVmExtensionPoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GlobalVmExtensionPoliciesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> GlobalVmExtensionPoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + GlobalVmExtensionPoliciesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = GlobalVmExtensionPoliciesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = GlobalVmExtensionPoliciesClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = GlobalVmExtensionPoliciesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = GlobalVmExtensionPoliciesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + GlobalVmExtensionPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = GlobalVmExtensionPoliciesClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + GlobalVmExtensionPoliciesTransport, + Callable[..., GlobalVmExtensionPoliciesTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the global vm extension policies client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,GlobalVmExtensionPoliciesTransport,Callable[..., GlobalVmExtensionPoliciesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the GlobalVmExtensionPoliciesTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + GlobalVmExtensionPoliciesClient._read_environment_variables() + ) + self._client_cert_source = ( + GlobalVmExtensionPoliciesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = GlobalVmExtensionPoliciesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, GlobalVmExtensionPoliciesTransport) + if transport_provided: + # transport is a GlobalVmExtensionPoliciesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(GlobalVmExtensionPoliciesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or GlobalVmExtensionPoliciesClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[GlobalVmExtensionPoliciesTransport], + Callable[..., GlobalVmExtensionPoliciesTransport], + ] = ( + GlobalVmExtensionPoliciesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., GlobalVmExtensionPoliciesTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.compute_v1.GlobalVmExtensionPoliciesClient`.", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "credentialsType": None, + }, + ) + + def aggregated_list( + self, + request: Optional[ + Union[compute.AggregatedListGlobalVmExtensionPoliciesRequest, dict] + ] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AggregatedListPager: + r"""Retrieves the list of all VM Extension Policy resources + available to the specified project. + + To prevent failure, it's recommended that you set the + ``returnPartialSuccess`` parameter to ``true``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_aggregated_list(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.AggregatedListGlobalVmExtensionPoliciesRequest( + project="project_value", + ) + + # Make the request + page_result = client.aggregated_list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.AggregatedListGlobalVmExtensionPoliciesRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.AggregatedList. + See the method description for details. + project (str): + Name of the project scoping this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.services.global_vm_extension_policies.pagers.AggregatedListPager: + Response for the aggregated list of + VM extension policies. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, compute.AggregatedListGlobalVmExtensionPoliciesRequest + ): + request = compute.AggregatedListGlobalVmExtensionPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.aggregated_list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.AggregatedListPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_unary( + self, + request: Optional[ + Union[compute.DeleteGlobalVmExtensionPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + global_vm_extension_policy: Optional[str] = None, + global_vm_extension_policy_rollout_operation_rollout_input_resource: Optional[ + compute.GlobalVmExtensionPolicyRolloutOperationRolloutInput + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Purge scoped resources (zonal policies) from a global + VM extension policy, and then delete the global VM + extension policy. Purge of the scoped resources is a + pre-condition of the global VM extension policy + deletion. The deletion of the global VM extension policy + happens after the purge rollout is done, so it's not a + part of the LRO. It's an automatic process that triggers + in the backend. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.DeleteGlobalVmExtensionPolicyRequest( + global_vm_extension_policy="global_vm_extension_policy_value", + project="project_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteGlobalVmExtensionPolicyRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.Delete. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy (str): + Name of the global VM extension + policy to purge scoped resources for. + + This corresponds to the ``global_vm_extension_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy_rollout_operation_rollout_input_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutInput): + The body resource for this request + This corresponds to the ``global_vm_extension_policy_rollout_operation_rollout_input_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + global_vm_extension_policy, + global_vm_extension_policy_rollout_operation_rollout_input_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.DeleteGlobalVmExtensionPolicyRequest): + request = compute.DeleteGlobalVmExtensionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if global_vm_extension_policy is not None: + request.global_vm_extension_policy = global_vm_extension_policy + if ( + global_vm_extension_policy_rollout_operation_rollout_input_resource + is not None + ): + request.global_vm_extension_policy_rollout_operation_rollout_input_resource = global_vm_extension_policy_rollout_operation_rollout_input_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("global_vm_extension_policy", request.global_vm_extension_policy), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete( + self, + request: Optional[ + Union[compute.DeleteGlobalVmExtensionPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + global_vm_extension_policy: Optional[str] = None, + global_vm_extension_policy_rollout_operation_rollout_input_resource: Optional[ + compute.GlobalVmExtensionPolicyRolloutOperationRolloutInput + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Purge scoped resources (zonal policies) from a global + VM extension policy, and then delete the global VM + extension policy. Purge of the scoped resources is a + pre-condition of the global VM extension policy + deletion. The deletion of the global VM extension policy + happens after the purge rollout is done, so it's not a + part of the LRO. It's an automatic process that triggers + in the backend. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.DeleteGlobalVmExtensionPolicyRequest( + global_vm_extension_policy="global_vm_extension_policy_value", + project="project_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteGlobalVmExtensionPolicyRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.Delete. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy (str): + Name of the global VM extension + policy to purge scoped resources for. + + This corresponds to the ``global_vm_extension_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy_rollout_operation_rollout_input_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutInput): + The body resource for this request + This corresponds to the ``global_vm_extension_policy_rollout_operation_rollout_input_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + global_vm_extension_policy, + global_vm_extension_policy_rollout_operation_rollout_input_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.DeleteGlobalVmExtensionPolicyRequest): + request = compute.DeleteGlobalVmExtensionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if global_vm_extension_policy is not None: + request.global_vm_extension_policy = global_vm_extension_policy + if ( + global_vm_extension_policy_rollout_operation_rollout_input_resource + is not None + ): + request.global_vm_extension_policy_rollout_operation_rollout_input_resource = global_vm_extension_policy_rollout_operation_rollout_input_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("global_vm_extension_policy", request.global_vm_extension_policy), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def get( + self, + request: Optional[ + Union[compute.GetGlobalVmExtensionPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + global_vm_extension_policy: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.GlobalVmExtensionPolicy: + r"""Gets details of a global VM extension policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.GetGlobalVmExtensionPolicyRequest( + global_vm_extension_policy="global_vm_extension_policy_value", + project="project_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetGlobalVmExtensionPolicyRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.Get. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy (str): + Name of the GlobalVmExtensionPolicy + resource to return. + + This corresponds to the ``global_vm_extension_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.GlobalVmExtensionPolicy: + Message describing + GlobalVmExtensionPolicy object. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, global_vm_extension_policy] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetGlobalVmExtensionPolicyRequest): + request = compute.GetGlobalVmExtensionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if global_vm_extension_policy is not None: + request.global_vm_extension_policy = global_vm_extension_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("global_vm_extension_policy", request.global_vm_extension_policy), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_unary( + self, + request: Optional[ + Union[compute.InsertGlobalVmExtensionPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + global_vm_extension_policy_resource: Optional[ + compute.GlobalVmExtensionPolicy + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Creates a new project level GlobalVmExtensionPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_insert(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.InsertGlobalVmExtensionPolicyRequest( + project="project_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertGlobalVmExtensionPolicyRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.Insert. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicy): + The body resource for this request + This corresponds to the ``global_vm_extension_policy_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, global_vm_extension_policy_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.InsertGlobalVmExtensionPolicyRequest): + request = compute.InsertGlobalVmExtensionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if global_vm_extension_policy_resource is not None: + request.global_vm_extension_policy_resource = ( + global_vm_extension_policy_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert( + self, + request: Optional[ + Union[compute.InsertGlobalVmExtensionPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + global_vm_extension_policy_resource: Optional[ + compute.GlobalVmExtensionPolicy + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Creates a new project level GlobalVmExtensionPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_insert(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.InsertGlobalVmExtensionPolicyRequest( + project="project_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertGlobalVmExtensionPolicyRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.Insert. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicy): + The body resource for this request + This corresponds to the ``global_vm_extension_policy_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, global_vm_extension_policy_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.InsertGlobalVmExtensionPolicyRequest): + request = compute.InsertGlobalVmExtensionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if global_vm_extension_policy_resource is not None: + request.global_vm_extension_policy_resource = ( + global_vm_extension_policy_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def list( + self, + request: Optional[ + Union[compute.ListGlobalVmExtensionPoliciesRequest, dict] + ] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPager: + r"""Lists global VM extension policies. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_list(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.ListGlobalVmExtensionPoliciesRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListGlobalVmExtensionPoliciesRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.List. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.services.global_vm_extension_policies.pagers.ListPager: + Response to list global VM extension + policy resources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.ListGlobalVmExtensionPoliciesRequest): + request = compute.ListGlobalVmExtensionPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_unary( + self, + request: Optional[ + Union[compute.UpdateGlobalVmExtensionPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + global_vm_extension_policy: Optional[str] = None, + global_vm_extension_policy_resource: Optional[ + compute.GlobalVmExtensionPolicy + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Updates a global VM extension policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_update(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.UpdateGlobalVmExtensionPolicyRequest( + global_vm_extension_policy="global_vm_extension_policy_value", + project="project_value", + ) + + # Make the request + response = client.update(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.UpdateGlobalVmExtensionPolicyRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.Update. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy (str): + Name of the global VM extension + policy to update. + + This corresponds to the ``global_vm_extension_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicy): + The body resource for this request + This corresponds to the ``global_vm_extension_policy_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + global_vm_extension_policy, + global_vm_extension_policy_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.UpdateGlobalVmExtensionPolicyRequest): + request = compute.UpdateGlobalVmExtensionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if global_vm_extension_policy is not None: + request.global_vm_extension_policy = global_vm_extension_policy + if global_vm_extension_policy_resource is not None: + request.global_vm_extension_policy_resource = ( + global_vm_extension_policy_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("global_vm_extension_policy", request.global_vm_extension_policy), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update( + self, + request: Optional[ + Union[compute.UpdateGlobalVmExtensionPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + global_vm_extension_policy: Optional[str] = None, + global_vm_extension_policy_resource: Optional[ + compute.GlobalVmExtensionPolicy + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Updates a global VM extension policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_update(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.UpdateGlobalVmExtensionPolicyRequest( + global_vm_extension_policy="global_vm_extension_policy_value", + project="project_value", + ) + + # Make the request + response = client.update(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.UpdateGlobalVmExtensionPolicyRequest, dict]): + The request object. A request message for + GlobalVmExtensionPolicies.Update. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy (str): + Name of the global VM extension + policy to update. + + This corresponds to the ``global_vm_extension_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_vm_extension_policy_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicy): + The body resource for this request + This corresponds to the ``global_vm_extension_policy_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + global_vm_extension_policy, + global_vm_extension_policy_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.UpdateGlobalVmExtensionPolicyRequest): + request = compute.UpdateGlobalVmExtensionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if global_vm_extension_policy is not None: + request.global_vm_extension_policy = global_vm_extension_policy + if global_vm_extension_policy_resource is not None: + request.global_vm_extension_policy_resource = ( + global_vm_extension_policy_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("global_vm_extension_policy", request.global_vm_extension_policy), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def __enter__(self) -> "GlobalVmExtensionPoliciesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("GlobalVmExtensionPoliciesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/pagers.py new file mode 100644 index 000000000000..507a1b0cf094 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/pagers.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.compute_v1.types import compute + + +class AggregatedListPager: + """A pager for iterating through ``aggregated_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.VmExtensionPolicyAggregatedListResponse` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``AggregatedList`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.VmExtensionPolicyAggregatedListResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., compute.VmExtensionPolicyAggregatedListResponse], + request: compute.AggregatedListGlobalVmExtensionPoliciesRequest, + response: compute.VmExtensionPolicyAggregatedListResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.compute_v1.types.AggregatedListGlobalVmExtensionPoliciesRequest): + The initial request object. + response (google.cloud.compute_v1.types.VmExtensionPolicyAggregatedListResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = compute.AggregatedListGlobalVmExtensionPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.VmExtensionPolicyAggregatedListResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[Tuple[str, compute.VmExtensionPoliciesScopedList]]: + for page in self.pages: + yield from page.items.items() + + def get(self, key: str) -> Optional[compute.VmExtensionPoliciesScopedList]: + return self._response.items.get(key) + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPager: + """A pager for iterating through ``list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.GlobalVmExtensionPolicyList` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``List`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.GlobalVmExtensionPolicyList` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., compute.GlobalVmExtensionPolicyList], + request: compute.ListGlobalVmExtensionPoliciesRequest, + response: compute.GlobalVmExtensionPolicyList, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.compute_v1.types.ListGlobalVmExtensionPoliciesRequest): + The initial request object. + response (google.cloud.compute_v1.types.GlobalVmExtensionPolicyList): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = compute.ListGlobalVmExtensionPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.GlobalVmExtensionPolicyList]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[compute.GlobalVmExtensionPolicy]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/README.rst b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/README.rst new file mode 100644 index 000000000000..e35d3b2af007 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``GlobalVmExtensionPoliciesTransport`` is the ABC for all transports. + +- public child ``GlobalVmExtensionPoliciesGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``GlobalVmExtensionPoliciesGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseGlobalVmExtensionPoliciesRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``GlobalVmExtensionPoliciesRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/__init__.py new file mode 100644 index 000000000000..13e387231f84 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import GlobalVmExtensionPoliciesTransport +from .rest import ( + GlobalVmExtensionPoliciesRestInterceptor, + GlobalVmExtensionPoliciesRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GlobalVmExtensionPoliciesTransport]] +_transport_registry["rest"] = GlobalVmExtensionPoliciesRestTransport + +__all__ = ( + "GlobalVmExtensionPoliciesTransport", + "GlobalVmExtensionPoliciesRestTransport", + "GlobalVmExtensionPoliciesRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/base.py new file mode 100644 index 000000000000..f4edb8c0e2b6 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/base.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.services import global_operations +from google.cloud.compute_v1.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class GlobalVmExtensionPoliciesTransport(abc.ABC): + """Abstract transport class for GlobalVmExtensionPolicies.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + self._extended_operations_services: Dict[str, Any] = {} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.aggregated_list: gapic_v1.method.wrap_method( + self.aggregated_list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=600.0, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=600.0, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update: gapic_v1.method.wrap_method( + self.update, + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListGlobalVmExtensionPoliciesRequest], + Union[ + compute.VmExtensionPolicyAggregatedListResponse, + Awaitable[compute.VmExtensionPolicyAggregatedListResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteGlobalVmExtensionPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetGlobalVmExtensionPolicyRequest], + Union[ + compute.GlobalVmExtensionPolicy, Awaitable[compute.GlobalVmExtensionPolicy] + ], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertGlobalVmExtensionPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListGlobalVmExtensionPoliciesRequest], + Union[ + compute.GlobalVmExtensionPolicyList, + Awaitable[compute.GlobalVmExtensionPolicyList], + ], + ]: + raise NotImplementedError() + + @property + def update( + self, + ) -> Callable[ + [compute.UpdateGlobalVmExtensionPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _global_operations_client(self) -> global_operations.GlobalOperationsClient: + ex_op_service = self._extended_operations_services.get("global_operations") + if not ex_op_service: + ex_op_service = global_operations.GlobalOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["global_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("GlobalVmExtensionPoliciesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/rest.py new file mode 100644 index 000000000000..ca30a0776af6 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/rest.py @@ -0,0 +1,1572 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseGlobalVmExtensionPoliciesRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class GlobalVmExtensionPoliciesRestInterceptor: + """Interceptor for GlobalVmExtensionPolicies. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the GlobalVmExtensionPoliciesRestTransport. + + .. code-block:: python + class MyCustomGlobalVmExtensionPoliciesInterceptor(GlobalVmExtensionPoliciesRestInterceptor): + def pre_aggregated_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_aggregated_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_insert(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GlobalVmExtensionPoliciesRestTransport(interceptor=MyCustomGlobalVmExtensionPoliciesInterceptor()) + client = GlobalVmExtensionPoliciesClient(transport=transport) + + + """ + + def pre_aggregated_list( + self, + request: compute.AggregatedListGlobalVmExtensionPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.AggregatedListGlobalVmExtensionPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for aggregated_list + + Override in a subclass to manipulate the request or metadata + before they are sent to the GlobalVmExtensionPolicies server. + """ + return request, metadata + + def post_aggregated_list( + self, response: compute.VmExtensionPolicyAggregatedListResponse + ) -> compute.VmExtensionPolicyAggregatedListResponse: + """Post-rpc interceptor for aggregated_list + + DEPRECATED. Please use the `post_aggregated_list_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GlobalVmExtensionPolicies server but before + it is returned to user code. This `post_aggregated_list` interceptor runs + before the `post_aggregated_list_with_metadata` interceptor. + """ + return response + + def post_aggregated_list_with_metadata( + self, + response: compute.VmExtensionPolicyAggregatedListResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.VmExtensionPolicyAggregatedListResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for aggregated_list + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GlobalVmExtensionPolicies server but before it is returned to user code. + + We recommend only using this `post_aggregated_list_with_metadata` + interceptor in new development instead of the `post_aggregated_list` interceptor. + When both interceptors are used, this `post_aggregated_list_with_metadata` interceptor runs after the + `post_aggregated_list` interceptor. The (possibly modified) response returned by + `post_aggregated_list` will be passed to + `post_aggregated_list_with_metadata`. + """ + return response, metadata + + def pre_delete( + self, + request: compute.DeleteGlobalVmExtensionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.DeleteGlobalVmExtensionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete + + Override in a subclass to manipulate the request or metadata + before they are sent to the GlobalVmExtensionPolicies server. + """ + return request, metadata + + def post_delete(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete + + DEPRECATED. Please use the `post_delete_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GlobalVmExtensionPolicies server but before + it is returned to user code. This `post_delete` interceptor runs + before the `post_delete_with_metadata` interceptor. + """ + return response + + def post_delete_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GlobalVmExtensionPolicies server but before it is returned to user code. + + We recommend only using this `post_delete_with_metadata` + interceptor in new development instead of the `post_delete` interceptor. + When both interceptors are used, this `post_delete_with_metadata` interceptor runs after the + `post_delete` interceptor. The (possibly modified) response returned by + `post_delete` will be passed to + `post_delete_with_metadata`. + """ + return response, metadata + + def pre_get( + self, + request: compute.GetGlobalVmExtensionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetGlobalVmExtensionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the GlobalVmExtensionPolicies server. + """ + return request, metadata + + def post_get( + self, response: compute.GlobalVmExtensionPolicy + ) -> compute.GlobalVmExtensionPolicy: + """Post-rpc interceptor for get + + DEPRECATED. Please use the `post_get_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GlobalVmExtensionPolicies server but before + it is returned to user code. This `post_get` interceptor runs + before the `post_get_with_metadata` interceptor. + """ + return response + + def post_get_with_metadata( + self, + response: compute.GlobalVmExtensionPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GlobalVmExtensionPolicy, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GlobalVmExtensionPolicies server but before it is returned to user code. + + We recommend only using this `post_get_with_metadata` + interceptor in new development instead of the `post_get` interceptor. + When both interceptors are used, this `post_get_with_metadata` interceptor runs after the + `post_get` interceptor. The (possibly modified) response returned by + `post_get` will be passed to + `post_get_with_metadata`. + """ + return response, metadata + + def pre_insert( + self, + request: compute.InsertGlobalVmExtensionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.InsertGlobalVmExtensionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for insert + + Override in a subclass to manipulate the request or metadata + before they are sent to the GlobalVmExtensionPolicies server. + """ + return request, metadata + + def post_insert(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for insert + + DEPRECATED. Please use the `post_insert_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GlobalVmExtensionPolicies server but before + it is returned to user code. This `post_insert` interceptor runs + before the `post_insert_with_metadata` interceptor. + """ + return response + + def post_insert_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GlobalVmExtensionPolicies server but before it is returned to user code. + + We recommend only using this `post_insert_with_metadata` + interceptor in new development instead of the `post_insert` interceptor. + When both interceptors are used, this `post_insert_with_metadata` interceptor runs after the + `post_insert` interceptor. The (possibly modified) response returned by + `post_insert` will be passed to + `post_insert_with_metadata`. + """ + return response, metadata + + def pre_list( + self, + request: compute.ListGlobalVmExtensionPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListGlobalVmExtensionPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list + + Override in a subclass to manipulate the request or metadata + before they are sent to the GlobalVmExtensionPolicies server. + """ + return request, metadata + + def post_list( + self, response: compute.GlobalVmExtensionPolicyList + ) -> compute.GlobalVmExtensionPolicyList: + """Post-rpc interceptor for list + + DEPRECATED. Please use the `post_list_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GlobalVmExtensionPolicies server but before + it is returned to user code. This `post_list` interceptor runs + before the `post_list_with_metadata` interceptor. + """ + return response + + def post_list_with_metadata( + self, + response: compute.GlobalVmExtensionPolicyList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GlobalVmExtensionPolicyList, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GlobalVmExtensionPolicies server but before it is returned to user code. + + We recommend only using this `post_list_with_metadata` + interceptor in new development instead of the `post_list` interceptor. + When both interceptors are used, this `post_list_with_metadata` interceptor runs after the + `post_list` interceptor. The (possibly modified) response returned by + `post_list` will be passed to + `post_list_with_metadata`. + """ + return response, metadata + + def pre_update( + self, + request: compute.UpdateGlobalVmExtensionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.UpdateGlobalVmExtensionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update + + Override in a subclass to manipulate the request or metadata + before they are sent to the GlobalVmExtensionPolicies server. + """ + return request, metadata + + def post_update(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for update + + DEPRECATED. Please use the `post_update_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GlobalVmExtensionPolicies server but before + it is returned to user code. This `post_update` interceptor runs + before the `post_update_with_metadata` interceptor. + """ + return response + + def post_update_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GlobalVmExtensionPolicies server but before it is returned to user code. + + We recommend only using this `post_update_with_metadata` + interceptor in new development instead of the `post_update` interceptor. + When both interceptors are used, this `post_update_with_metadata` interceptor runs after the + `post_update` interceptor. The (possibly modified) response returned by + `post_update` will be passed to + `post_update_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class GlobalVmExtensionPoliciesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GlobalVmExtensionPoliciesRestInterceptor + + +class GlobalVmExtensionPoliciesRestTransport( + _BaseGlobalVmExtensionPoliciesRestTransport +): + """REST backend synchronous transport for GlobalVmExtensionPolicies. + + The GlobalVmExtensionPolicies API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[GlobalVmExtensionPoliciesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[GlobalVmExtensionPoliciesRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or GlobalVmExtensionPoliciesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AggregatedList( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseAggregatedList, + GlobalVmExtensionPoliciesRestStub, + ): + def __hash__(self): + return hash("GlobalVmExtensionPoliciesRestTransport.AggregatedList") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.AggregatedListGlobalVmExtensionPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.VmExtensionPolicyAggregatedListResponse: + r"""Call the aggregated list method over HTTP. + + Args: + request (~.compute.AggregatedListGlobalVmExtensionPoliciesRequest): + The request object. A request message for + GlobalVmExtensionPolicies.AggregatedList. + See the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.VmExtensionPolicyAggregatedListResponse: + Response for the aggregated list of + VM extension policies. + + """ + + http_options = _BaseGlobalVmExtensionPoliciesRestTransport._BaseAggregatedList._get_http_options() + + request, metadata = self._interceptor.pre_aggregated_list(request, metadata) + transcoded_request = _BaseGlobalVmExtensionPoliciesRestTransport._BaseAggregatedList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGlobalVmExtensionPoliciesRestTransport._BaseAggregatedList._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.AggregatedList", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "AggregatedList", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + GlobalVmExtensionPoliciesRestTransport._AggregatedList._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.VmExtensionPolicyAggregatedListResponse() + pb_resp = compute.VmExtensionPolicyAggregatedListResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_aggregated_list(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_aggregated_list_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + compute.VmExtensionPolicyAggregatedListResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.aggregated_list", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "AggregatedList", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Delete( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseDelete, + GlobalVmExtensionPoliciesRestStub, + ): + def __hash__(self): + return hash("GlobalVmExtensionPoliciesRestTransport.Delete") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.DeleteGlobalVmExtensionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteGlobalVmExtensionPolicyRequest): + The request object. A request message for + GlobalVmExtensionPolicies.Delete. See + the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseGlobalVmExtensionPoliciesRestTransport._BaseDelete._get_http_options() + + request, metadata = self._interceptor.pre_delete(request, metadata) + transcoded_request = _BaseGlobalVmExtensionPoliciesRestTransport._BaseDelete._get_transcoded_request( + http_options, request + ) + + body = _BaseGlobalVmExtensionPoliciesRestTransport._BaseDelete._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGlobalVmExtensionPoliciesRestTransport._BaseDelete._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.Delete", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "Delete", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GlobalVmExtensionPoliciesRestTransport._Delete._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.delete", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "Delete", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Get( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseGet, + GlobalVmExtensionPoliciesRestStub, + ): + def __hash__(self): + return hash("GlobalVmExtensionPoliciesRestTransport.Get") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetGlobalVmExtensionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.GlobalVmExtensionPolicy: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetGlobalVmExtensionPolicyRequest): + The request object. A request message for + GlobalVmExtensionPolicies.Get. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.GlobalVmExtensionPolicy: + Message describing + GlobalVmExtensionPolicy object. + + """ + + http_options = ( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = _BaseGlobalVmExtensionPoliciesRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGlobalVmExtensionPoliciesRestTransport._BaseGet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GlobalVmExtensionPoliciesRestTransport._Get._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.GlobalVmExtensionPolicy() + pb_resp = compute.GlobalVmExtensionPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.GlobalVmExtensionPolicy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.get", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Insert( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseInsert, + GlobalVmExtensionPoliciesRestStub, + ): + def __hash__(self): + return hash("GlobalVmExtensionPoliciesRestTransport.Insert") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.InsertGlobalVmExtensionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertGlobalVmExtensionPolicyRequest): + The request object. A request message for + GlobalVmExtensionPolicies.Insert. See + the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseGlobalVmExtensionPoliciesRestTransport._BaseInsert._get_http_options() + + request, metadata = self._interceptor.pre_insert(request, metadata) + transcoded_request = _BaseGlobalVmExtensionPoliciesRestTransport._BaseInsert._get_transcoded_request( + http_options, request + ) + + body = _BaseGlobalVmExtensionPoliciesRestTransport._BaseInsert._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGlobalVmExtensionPoliciesRestTransport._BaseInsert._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.Insert", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "Insert", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GlobalVmExtensionPoliciesRestTransport._Insert._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.insert", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "Insert", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseList, + GlobalVmExtensionPoliciesRestStub, + ): + def __hash__(self): + return hash("GlobalVmExtensionPoliciesRestTransport.List") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.ListGlobalVmExtensionPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.GlobalVmExtensionPolicyList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListGlobalVmExtensionPoliciesRequest): + The request object. A request message for + GlobalVmExtensionPolicies.List. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.GlobalVmExtensionPolicyList: + Response to list global VM extension + policy resources. + + """ + + http_options = _BaseGlobalVmExtensionPoliciesRestTransport._BaseList._get_http_options() + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = _BaseGlobalVmExtensionPoliciesRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGlobalVmExtensionPoliciesRestTransport._BaseList._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.List", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GlobalVmExtensionPoliciesRestTransport._List._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.GlobalVmExtensionPolicyList() + pb_resp = compute.GlobalVmExtensionPolicyList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.GlobalVmExtensionPolicyList.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.list", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Update( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseUpdate, + GlobalVmExtensionPoliciesRestStub, + ): + def __hash__(self): + return hash("GlobalVmExtensionPoliciesRestTransport.Update") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.UpdateGlobalVmExtensionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the update method over HTTP. + + Args: + request (~.compute.UpdateGlobalVmExtensionPolicyRequest): + The request object. A request message for + GlobalVmExtensionPolicies.Update. See + the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseGlobalVmExtensionPoliciesRestTransport._BaseUpdate._get_http_options() + + request, metadata = self._interceptor.pre_update(request, metadata) + transcoded_request = _BaseGlobalVmExtensionPoliciesRestTransport._BaseUpdate._get_transcoded_request( + http_options, request + ) + + body = _BaseGlobalVmExtensionPoliciesRestTransport._BaseUpdate._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGlobalVmExtensionPoliciesRestTransport._BaseUpdate._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.Update", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "Update", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GlobalVmExtensionPoliciesRestTransport._Update._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.update", + extra={ + "serviceName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "rpcName": "Update", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListGlobalVmExtensionPoliciesRequest], + compute.VmExtensionPolicyAggregatedListResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AggregatedList(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete( + self, + ) -> Callable[[compute.DeleteGlobalVmExtensionPolicyRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Delete(self._session, self._host, self._interceptor) # type: ignore + + @property + def get( + self, + ) -> Callable[ + [compute.GetGlobalVmExtensionPolicyRequest], compute.GlobalVmExtensionPolicy + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert( + self, + ) -> Callable[[compute.InsertGlobalVmExtensionPolicyRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Insert(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[ + [compute.ListGlobalVmExtensionPoliciesRequest], + compute.GlobalVmExtensionPolicyList, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._List(self._session, self._host, self._interceptor) # type: ignore + + @property + def update( + self, + ) -> Callable[[compute.UpdateGlobalVmExtensionPolicyRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Update(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("GlobalVmExtensionPoliciesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/rest_base.py new file mode 100644 index 000000000000..19c1c5813745 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_vm_extension_policies/transports/rest_base.py @@ -0,0 +1,399 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO, GlobalVmExtensionPoliciesTransport + + +class _BaseGlobalVmExtensionPoliciesRestTransport(GlobalVmExtensionPoliciesTransport): + """Base REST backend transport for GlobalVmExtensionPolicies. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseAggregatedList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/aggregated/vmExtensionPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AggregatedListGlobalVmExtensionPoliciesRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseAggregatedList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseDelete: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/global/vmExtensionPolicies/{global_vm_extension_policy}/delete", + "body": "global_vm_extension_policy_rollout_operation_rollout_input_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteGlobalVmExtensionPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseDelete._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseGet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/global/vmExtensionPolicies/{global_vm_extension_policy}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetGlobalVmExtensionPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseInsert: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/global/vmExtensionPolicies", + "body": "global_vm_extension_policy_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.InsertGlobalVmExtensionPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseInsert._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/global/vmExtensionPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListGlobalVmExtensionPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseUpdate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/compute/v1/projects/{project}/global/vmExtensionPolicies/{global_vm_extension_policy}", + "body": "global_vm_extension_policy_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.UpdateGlobalVmExtensionPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseGlobalVmExtensionPoliciesRestTransport._BaseUpdate._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseGlobalVmExtensionPoliciesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py index e2b7a9ef60a0..67cd416e8e1e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py @@ -830,6 +830,326 @@ def sample_get(): # Done; return the response. return response + def get_iam_policy( + self, + request: Optional[Union[compute.GetIamPolicyLicenseCodeRequest, dict]] = None, + *, + project: Optional[str] = None, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Gets the access control policy for a resource. May be empty if + no such policy or resource exists. *Caution* This resource is + intended for use only by third-party partners who are + creatingCloud Marketplace images. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get_iam_policy(): + # Create a client + client = compute_v1.LicenseCodesClient() + + # Initialize request argument(s) + request = compute_v1.GetIamPolicyLicenseCodeRequest( + project="project_value", + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetIamPolicyLicenseCodeRequest, dict]): + The request object. A request message for + LicenseCodes.GetIamPolicy. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetIamPolicyLicenseCodeRequest): + request = compute.GetIamPolicyLicenseCodeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[Union[compute.SetIamPolicyLicenseCodeRequest, dict]] = None, + *, + project: Optional[str] = None, + resource: Optional[str] = None, + global_set_policy_request_resource: Optional[ + compute.GlobalSetPolicyRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Sets the access control policy on the specified resource. + Replaces any existing policy. *Caution* This resource is + intended for use only by third-party partners who are + creatingCloud Marketplace images. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_iam_policy(): + # Create a client + client = compute_v1.LicenseCodesClient() + + # Initialize request argument(s) + request = compute_v1.SetIamPolicyLicenseCodeRequest( + project="project_value", + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetIamPolicyLicenseCodeRequest, dict]): + The request object. A request message for + LicenseCodes.SetIamPolicy. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + global_set_policy_request_resource (google.cloud.compute_v1.types.GlobalSetPolicyRequest): + The body resource for this request + This corresponds to the ``global_set_policy_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, resource, global_set_policy_request_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.SetIamPolicyLicenseCodeRequest): + request = compute.SetIamPolicyLicenseCodeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if resource is not None: + request.resource = resource + if global_set_policy_request_resource is not None: + request.global_set_policy_request_resource = ( + global_set_policy_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def test_iam_permissions( self, request: Optional[ diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/base.py index 68f69cc77ff2..ccb6c1ab0100 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/base.py @@ -40,7 +40,6 @@ class LicenseCodesTransport(abc.ABC): """Abstract transport class for LicenseCodes.""" AUTH_SCOPES = ( - "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ) @@ -161,6 +160,26 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=600.0, + client_info=client_info, + ), self.test_iam_permissions: gapic_v1.method.wrap_method( self.test_iam_permissions, default_timeout=600.0, @@ -186,6 +205,24 @@ def get( ]: raise NotImplementedError() + @property + def get_iam_policy( + self, + ) -> Callable[ + [compute.GetIamPolicyLicenseCodeRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [compute.SetIamPolicyLicenseCodeRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + @property def test_iam_permissions( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest.py index 6e2dbf8a8557..f480600fb6a5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest.py @@ -80,6 +80,22 @@ def post_get(self, response): logging.log(f"Received response: {response}") return response + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_test_iam_permissions(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -138,6 +154,98 @@ def post_get_with_metadata( """ return response, metadata + def pre_get_iam_policy( + self, + request: compute.GetIamPolicyLicenseCodeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetIamPolicyLicenseCodeRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the LicenseCodes server. + """ + return request, metadata + + def post_get_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for get_iam_policy + + DEPRECATED. Please use the `post_get_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LicenseCodes server but before + it is returned to user code. This `post_get_iam_policy` interceptor runs + before the `post_get_iam_policy_with_metadata` interceptor. + """ + return response + + def post_get_iam_policy_with_metadata( + self, + response: compute.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LicenseCodes server but before it is returned to user code. + + We recommend only using this `post_get_iam_policy_with_metadata` + interceptor in new development instead of the `post_get_iam_policy` interceptor. + When both interceptors are used, this `post_get_iam_policy_with_metadata` interceptor runs after the + `post_get_iam_policy` interceptor. The (possibly modified) response returned by + `post_get_iam_policy` will be passed to + `post_get_iam_policy_with_metadata`. + """ + return response, metadata + + def pre_set_iam_policy( + self, + request: compute.SetIamPolicyLicenseCodeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.SetIamPolicyLicenseCodeRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the LicenseCodes server. + """ + return request, metadata + + def post_set_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for set_iam_policy + + DEPRECATED. Please use the `post_set_iam_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LicenseCodes server but before + it is returned to user code. This `post_set_iam_policy` interceptor runs + before the `post_set_iam_policy_with_metadata` interceptor. + """ + return response + + def post_set_iam_policy_with_metadata( + self, + response: compute.Policy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Policy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LicenseCodes server but before it is returned to user code. + + We recommend only using this `post_set_iam_policy_with_metadata` + interceptor in new development instead of the `post_set_iam_policy` interceptor. + When both interceptors are used, this `post_set_iam_policy_with_metadata` interceptor runs after the + `post_set_iam_policy` interceptor. The (possibly modified) response returned by + `post_set_iam_policy` will be passed to + `post_set_iam_policy_with_metadata`. + """ + return response, metadata + def pre_test_iam_permissions( self, request: compute.TestIamPermissionsLicenseCodeRequest, @@ -437,6 +545,458 @@ def __call__( ) return resp + class _GetIamPolicy( + _BaseLicenseCodesRestTransport._BaseGetIamPolicy, LicenseCodesRestStub + ): + def __hash__(self): + return hash("LicenseCodesRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetIamPolicyLicenseCodeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.compute.GetIamPolicyLicenseCodeRequest): + The request object. A request message for + LicenseCodes.GetIamPolicy. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options = ( + _BaseLicenseCodesRestTransport._BaseGetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseLicenseCodesRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseLicenseCodesRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.LicenseCodesClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.compute.v1.LicenseCodes", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LicenseCodesRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Policy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.LicenseCodesClient.get_iam_policy", + extra={ + "serviceName": "google.cloud.compute.v1.LicenseCodes", + "rpcName": "GetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SetIamPolicy( + _BaseLicenseCodesRestTransport._BaseSetIamPolicy, LicenseCodesRestStub + ): + def __hash__(self): + return hash("LicenseCodesRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.SetIamPolicyLicenseCodeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.compute.SetIamPolicyLicenseCodeRequest): + The request object. A request message for + LicenseCodes.SetIamPolicy. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options = ( + _BaseLicenseCodesRestTransport._BaseSetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseLicenseCodesRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseLicenseCodesRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseLicenseCodesRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.LicenseCodesClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.compute.v1.LicenseCodes", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LicenseCodesRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_set_iam_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_set_iam_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Policy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.LicenseCodesClient.set_iam_policy", + extra={ + "serviceName": "google.cloud.compute.v1.LicenseCodes", + "rpcName": "SetIamPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _TestIamPermissions( _BaseLicenseCodesRestTransport._BaseTestIamPermissions, LicenseCodesRestStub ): @@ -595,6 +1155,22 @@ def get(self) -> Callable[[compute.GetLicenseCodeRequest], compute.LicenseCode]: # In C++ this would require a dynamic_cast return self._Get(self._session, self._host, self._interceptor) # type: ignore + @property + def get_iam_policy( + self, + ) -> Callable[[compute.GetIamPolicyLicenseCodeRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy( + self, + ) -> Callable[[compute.SetIamPolicyLicenseCodeRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + @property def test_iam_permissions( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest_base.py index 713de758ae42..cc914f3776a5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest_base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/transports/rest_base.py @@ -133,6 +133,108 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/global/licenseCodes/{resource}/getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetIamPolicyLicenseCodeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseLicenseCodesRestTransport._BaseGetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/global/licenseCodes/{resource}/setIamPolicy", + "body": "global_set_policy_request_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.SetIamPolicyLicenseCodeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseLicenseCodesRestTransport._BaseSetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseTestIamPermissions: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py index ddbfae83088c..15b52bdccb6b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py @@ -998,6 +998,322 @@ def error_code(self): # Done; return the response. return response + def cancel_request_remove_peering_unary( + self, + request: Optional[ + Union[compute.CancelRequestRemovePeeringNetworkRequest, dict] + ] = None, + *, + project: Optional[str] = None, + network: Optional[str] = None, + networks_cancel_request_remove_peering_request_resource: Optional[ + compute.NetworksCancelRequestRemovePeeringRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Cancel requests to remove a peering from the specified network. + Applicable only for PeeringConnection with + update_strategy=CONSENSUS. Cancels a request to remove a peering + from the specified network. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_cancel_request_remove_peering(): + # Create a client + client = compute_v1.NetworksClient() + + # Initialize request argument(s) + request = compute_v1.CancelRequestRemovePeeringNetworkRequest( + network="network_value", + project="project_value", + ) + + # Make the request + response = client.cancel_request_remove_peering(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CancelRequestRemovePeeringNetworkRequest, dict]): + The request object. A request message for + Networks.CancelRequestRemovePeering. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network (str): + Name of the network resource to + remove peering from. + + This corresponds to the ``network`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + networks_cancel_request_remove_peering_request_resource (google.cloud.compute_v1.types.NetworksCancelRequestRemovePeeringRequest): + The body resource for this request + This corresponds to the ``networks_cancel_request_remove_peering_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + network, + networks_cancel_request_remove_peering_request_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CancelRequestRemovePeeringNetworkRequest): + request = compute.CancelRequestRemovePeeringNetworkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if network is not None: + request.network = network + if networks_cancel_request_remove_peering_request_resource is not None: + request.networks_cancel_request_remove_peering_request_resource = ( + networks_cancel_request_remove_peering_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.cancel_request_remove_peering + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("network", request.network), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel_request_remove_peering( + self, + request: Optional[ + Union[compute.CancelRequestRemovePeeringNetworkRequest, dict] + ] = None, + *, + project: Optional[str] = None, + network: Optional[str] = None, + networks_cancel_request_remove_peering_request_resource: Optional[ + compute.NetworksCancelRequestRemovePeeringRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Cancel requests to remove a peering from the specified network. + Applicable only for PeeringConnection with + update_strategy=CONSENSUS. Cancels a request to remove a peering + from the specified network. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_cancel_request_remove_peering(): + # Create a client + client = compute_v1.NetworksClient() + + # Initialize request argument(s) + request = compute_v1.CancelRequestRemovePeeringNetworkRequest( + network="network_value", + project="project_value", + ) + + # Make the request + response = client.cancel_request_remove_peering(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CancelRequestRemovePeeringNetworkRequest, dict]): + The request object. A request message for + Networks.CancelRequestRemovePeering. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network (str): + Name of the network resource to + remove peering from. + + This corresponds to the ``network`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + networks_cancel_request_remove_peering_request_resource (google.cloud.compute_v1.types.NetworksCancelRequestRemovePeeringRequest): + The body resource for this request + This corresponds to the ``networks_cancel_request_remove_peering_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + network, + networks_cancel_request_remove_peering_request_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CancelRequestRemovePeeringNetworkRequest): + request = compute.CancelRequestRemovePeeringNetworkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if network is not None: + request.network = network + if networks_cancel_request_remove_peering_request_resource is not None: + request.networks_cancel_request_remove_peering_request_resource = ( + networks_cancel_request_remove_peering_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.cancel_request_remove_peering + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("network", request.network), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def delete_unary( self, request: Optional[Union[compute.DeleteNetworkRequest, dict]] = None, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/base.py index 6954bd5c266a..f52e9daa7a97 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/base.py @@ -152,6 +152,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.cancel_request_remove_peering: gapic_v1.method.wrap_method( + self.cancel_request_remove_peering, + default_timeout=600.0, + client_info=client_info, + ), self.delete: gapic_v1.method.wrap_method( self.delete, default_timeout=600.0, @@ -267,6 +272,15 @@ def add_peering( ]: raise NotImplementedError() + @property + def cancel_request_remove_peering( + self, + ) -> Callable[ + [compute.CancelRequestRemovePeeringNetworkRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def delete( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest.py index d539763f1655..77ba5ea7b446 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest.py @@ -80,6 +80,14 @@ def post_add_peering(self, response): logging.log(f"Received response: {response}") return response + def pre_cancel_request_remove_peering(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_cancel_request_remove_peering(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -220,6 +228,55 @@ def post_add_peering_with_metadata( """ return response, metadata + def pre_cancel_request_remove_peering( + self, + request: compute.CancelRequestRemovePeeringNetworkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CancelRequestRemovePeeringNetworkRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for cancel_request_remove_peering + + Override in a subclass to manipulate the request or metadata + before they are sent to the Networks server. + """ + return request, metadata + + def post_cancel_request_remove_peering( + self, response: compute.Operation + ) -> compute.Operation: + """Post-rpc interceptor for cancel_request_remove_peering + + DEPRECATED. Please use the `post_cancel_request_remove_peering_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Networks server but before + it is returned to user code. This `post_cancel_request_remove_peering` interceptor runs + before the `post_cancel_request_remove_peering_with_metadata` interceptor. + """ + return response + + def post_cancel_request_remove_peering_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for cancel_request_remove_peering + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Networks server but before it is returned to user code. + + We recommend only using this `post_cancel_request_remove_peering_with_metadata` + interceptor in new development instead of the `post_cancel_request_remove_peering` interceptor. + When both interceptors are used, this `post_cancel_request_remove_peering_with_metadata` interceptor runs after the + `post_cancel_request_remove_peering` interceptor. The (possibly modified) response returned by + `post_cancel_request_remove_peering` will be passed to + `post_cancel_request_remove_peering_with_metadata`. + """ + return response, metadata + def pre_delete( self, request: compute.DeleteNetworkRequest, @@ -1013,6 +1070,189 @@ def __call__( ) return resp + class _CancelRequestRemovePeering( + _BaseNetworksRestTransport._BaseCancelRequestRemovePeering, NetworksRestStub + ): + def __hash__(self): + return hash("NetworksRestTransport.CancelRequestRemovePeering") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.CancelRequestRemovePeeringNetworkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the cancel request remove + peering method over HTTP. + + Args: + request (~.compute.CancelRequestRemovePeeringNetworkRequest): + The request object. A request message for + Networks.CancelRequestRemovePeering. See + the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseNetworksRestTransport._BaseCancelRequestRemovePeering._get_http_options() + + request, metadata = self._interceptor.pre_cancel_request_remove_peering( + request, metadata + ) + transcoded_request = _BaseNetworksRestTransport._BaseCancelRequestRemovePeering._get_transcoded_request( + http_options, request + ) + + body = _BaseNetworksRestTransport._BaseCancelRequestRemovePeering._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseNetworksRestTransport._BaseCancelRequestRemovePeering._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.NetworksClient.CancelRequestRemovePeering", + extra={ + "serviceName": "google.cloud.compute.v1.Networks", + "rpcName": "CancelRequestRemovePeering", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworksRestTransport._CancelRequestRemovePeering._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_cancel_request_remove_peering(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_cancel_request_remove_peering_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.NetworksClient.cancel_request_remove_peering", + extra={ + "serviceName": "google.cloud.compute.v1.Networks", + "rpcName": "CancelRequestRemovePeering", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _Delete(_BaseNetworksRestTransport._BaseDelete, NetworksRestStub): def __hash__(self): return hash("NetworksRestTransport.Delete") @@ -2864,6 +3104,18 @@ def add_peering( # In C++ this would require a dynamic_cast return self._AddPeering(self._session, self._host, self._interceptor) # type: ignore + @property + def cancel_request_remove_peering( + self, + ) -> Callable[ + [compute.CancelRequestRemovePeeringNetworkRequest], compute.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CancelRequestRemovePeering( + self._session, self._host, self._interceptor + ) # type: ignore + @property def delete(self) -> Callable[[compute.DeleteNetworkRequest], compute.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest_base.py index 007ec4dd9d8b..dffbf8402fe7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest_base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/transports/rest_base.py @@ -143,6 +143,62 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseCancelRequestRemovePeering: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/global/networks/{network}/cancelRequestRemovePeering", + "body": "networks_cancel_request_remove_peering_request_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.CancelRequestRemovePeeringNetworkRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseNetworksRestTransport._BaseCancelRequestRemovePeering._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseDelete: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/__init__.py new file mode 100644 index 000000000000..585a56f93ed7 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RolloutPlansClient + +__all__ = ("RolloutPlansClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/client.py new file mode 100644 index 000000000000..667081b9fe48 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/client.py @@ -0,0 +1,1506 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import functools +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation, gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.extended_operation as extended_operation # type: ignore + +from google.cloud.compute_v1.services.rollout_plans import pagers +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, RolloutPlansTransport +from .transports.rest import RolloutPlansRestTransport + + +class RolloutPlansClientMeta(type): + """Metaclass for the RolloutPlans client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[RolloutPlansTransport]] + _transport_registry["rest"] = RolloutPlansRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RolloutPlansTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RolloutPlansClient(metaclass=RolloutPlansClientMeta): + """The RolloutPlans API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RolloutPlansClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RolloutPlansClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RolloutPlansTransport: + """Returns the transport used by the client instance. + + Returns: + RolloutPlansTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = RolloutPlansClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = RolloutPlansClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = RolloutPlansClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = RolloutPlansClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RolloutPlansClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RolloutPlansClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, RolloutPlansTransport, Callable[..., RolloutPlansTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the rollout plans client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RolloutPlansTransport,Callable[..., RolloutPlansTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RolloutPlansTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + RolloutPlansClient._read_environment_variables() + ) + self._client_cert_source = RolloutPlansClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RolloutPlansClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, RolloutPlansTransport) + if transport_provided: + # transport is a RolloutPlansTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(RolloutPlansTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or RolloutPlansClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[RolloutPlansTransport], Callable[..., RolloutPlansTransport] + ] = ( + RolloutPlansClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RolloutPlansTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.compute_v1.RolloutPlansClient`.", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "credentialsType": None, + }, + ) + + def delete_unary( + self, + request: Optional[Union[compute.DeleteRolloutPlanRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout_plan: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Deletes a RolloutPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRolloutPlanRequest( + project="project_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteRolloutPlanRequest, dict]): + The request object. A request message for + RolloutPlans.Delete. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan (str): + Name of the RolloutPlan resource to + delete. + + This corresponds to the ``rollout_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout_plan] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.DeleteRolloutPlanRequest): + request = compute.DeleteRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout_plan is not None: + request.rollout_plan = rollout_plan + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("rollout_plan", request.rollout_plan), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete( + self, + request: Optional[Union[compute.DeleteRolloutPlanRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout_plan: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes a RolloutPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRolloutPlanRequest( + project="project_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteRolloutPlanRequest, dict]): + The request object. A request message for + RolloutPlans.Delete. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan (str): + Name of the RolloutPlan resource to + delete. + + This corresponds to the ``rollout_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout_plan] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.DeleteRolloutPlanRequest): + request = compute.DeleteRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout_plan is not None: + request.rollout_plan = rollout_plan + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("rollout_plan", request.rollout_plan), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def get( + self, + request: Optional[Union[compute.GetRolloutPlanRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout_plan: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RolloutPlan: + r"""Gets details of a single project-scoped RolloutPlan. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.GetRolloutPlanRequest( + project="project_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetRolloutPlanRequest, dict]): + The request object. A request message for + RolloutPlans.Get. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan (str): + Name of the persistent rollout plan + to return. + + This corresponds to the ``rollout_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.RolloutPlan: + RolloutPlan resource. + + A RolloutPlan is the customer-defined + strategy to divide a large-scale change + into smaller increments, referred to as + "waves". Each wave targets a specific + portion of the overall affected area and + defines criteria that must be met before + progressing to the subsequent wave. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout_plan] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetRolloutPlanRequest): + request = compute.GetRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout_plan is not None: + request.rollout_plan = rollout_plan + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("rollout_plan", request.rollout_plan), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_unary( + self, + request: Optional[Union[compute.InsertRolloutPlanRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout_plan_resource: Optional[compute.RolloutPlan] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Creates a new RolloutPlan in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_insert(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.InsertRolloutPlanRequest( + project="project_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertRolloutPlanRequest, dict]): + The request object. A request message for + RolloutPlans.Insert. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan_resource (google.cloud.compute_v1.types.RolloutPlan): + The body resource for this request + This corresponds to the ``rollout_plan_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout_plan_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.InsertRolloutPlanRequest): + request = compute.InsertRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout_plan_resource is not None: + request.rollout_plan_resource = rollout_plan_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert( + self, + request: Optional[Union[compute.InsertRolloutPlanRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout_plan_resource: Optional[compute.RolloutPlan] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Creates a new RolloutPlan in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_insert(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.InsertRolloutPlanRequest( + project="project_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertRolloutPlanRequest, dict]): + The request object. A request message for + RolloutPlans.Insert. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan_resource (google.cloud.compute_v1.types.RolloutPlan): + The body resource for this request + This corresponds to the ``rollout_plan_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout_plan_resource] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.InsertRolloutPlanRequest): + request = compute.InsertRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout_plan_resource is not None: + request.rollout_plan_resource = rollout_plan_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def list( + self, + request: Optional[Union[compute.ListRolloutPlansRequest, dict]] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPager: + r"""Lists RolloutPlans in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_list(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.ListRolloutPlansRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListRolloutPlansRequest, dict]): + The request object. A request message for + RolloutPlans.List. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.services.rollout_plans.pagers.ListPager: + Contains a list of RolloutPlan + resources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.ListRolloutPlansRequest): + request = compute.ListRolloutPlansRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RolloutPlansClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("RolloutPlansClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/pagers.py new file mode 100644 index 000000000000..ed2d696fa1ed --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.compute_v1.types import compute + + +class ListPager: + """A pager for iterating through ``list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.RolloutPlansListResponse` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``List`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.RolloutPlansListResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., compute.RolloutPlansListResponse], + request: compute.ListRolloutPlansRequest, + response: compute.RolloutPlansListResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.compute_v1.types.ListRolloutPlansRequest): + The initial request object. + response (google.cloud.compute_v1.types.RolloutPlansListResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = compute.ListRolloutPlansRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.RolloutPlansListResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[compute.RolloutPlan]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/README.rst b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/README.rst new file mode 100644 index 000000000000..f6c299524dec --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``RolloutPlansTransport`` is the ABC for all transports. + +- public child ``RolloutPlansGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``RolloutPlansGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseRolloutPlansRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``RolloutPlansRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/__init__.py new file mode 100644 index 000000000000..7d6a339a9e1a --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RolloutPlansTransport +from .rest import RolloutPlansRestInterceptor, RolloutPlansRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RolloutPlansTransport]] +_transport_registry["rest"] = RolloutPlansRestTransport + +__all__ = ( + "RolloutPlansTransport", + "RolloutPlansRestTransport", + "RolloutPlansRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/base.py new file mode 100644 index 000000000000..3b9a0a305457 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/base.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.services import global_operations +from google.cloud.compute_v1.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class RolloutPlansTransport(abc.ABC): + """Abstract transport class for RolloutPlans.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + self._extended_operations_services: Dict[str, Any] = {} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=600.0, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=600.0, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteRolloutPlanRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetRolloutPlanRequest], + Union[compute.RolloutPlan, Awaitable[compute.RolloutPlan]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertRolloutPlanRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListRolloutPlansRequest], + Union[ + compute.RolloutPlansListResponse, + Awaitable[compute.RolloutPlansListResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _global_operations_client(self) -> global_operations.GlobalOperationsClient: + ex_op_service = self._extended_operations_services.get("global_operations") + if not ex_op_service: + ex_op_service = global_operations.GlobalOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["global_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("RolloutPlansTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/rest.py new file mode 100644 index 000000000000..dd42ec25db68 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/rest.py @@ -0,0 +1,1090 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseRolloutPlansRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class RolloutPlansRestInterceptor: + """Interceptor for RolloutPlans. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RolloutPlansRestTransport. + + .. code-block:: python + class MyCustomRolloutPlansInterceptor(RolloutPlansRestInterceptor): + def pre_delete(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_insert(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RolloutPlansRestTransport(interceptor=MyCustomRolloutPlansInterceptor()) + client = RolloutPlansClient(transport=transport) + + + """ + + def pre_delete( + self, + request: compute.DeleteRolloutPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.DeleteRolloutPlanRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete + + Override in a subclass to manipulate the request or metadata + before they are sent to the RolloutPlans server. + """ + return request, metadata + + def post_delete(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete + + DEPRECATED. Please use the `post_delete_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RolloutPlans server but before + it is returned to user code. This `post_delete` interceptor runs + before the `post_delete_with_metadata` interceptor. + """ + return response + + def post_delete_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RolloutPlans server but before it is returned to user code. + + We recommend only using this `post_delete_with_metadata` + interceptor in new development instead of the `post_delete` interceptor. + When both interceptors are used, this `post_delete_with_metadata` interceptor runs after the + `post_delete` interceptor. The (possibly modified) response returned by + `post_delete` will be passed to + `post_delete_with_metadata`. + """ + return response, metadata + + def pre_get( + self, + request: compute.GetRolloutPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.GetRolloutPlanRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the RolloutPlans server. + """ + return request, metadata + + def post_get(self, response: compute.RolloutPlan) -> compute.RolloutPlan: + """Post-rpc interceptor for get + + DEPRECATED. Please use the `post_get_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RolloutPlans server but before + it is returned to user code. This `post_get` interceptor runs + before the `post_get_with_metadata` interceptor. + """ + return response + + def post_get_with_metadata( + self, + response: compute.RolloutPlan, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.RolloutPlan, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RolloutPlans server but before it is returned to user code. + + We recommend only using this `post_get_with_metadata` + interceptor in new development instead of the `post_get` interceptor. + When both interceptors are used, this `post_get_with_metadata` interceptor runs after the + `post_get` interceptor. The (possibly modified) response returned by + `post_get` will be passed to + `post_get_with_metadata`. + """ + return response, metadata + + def pre_insert( + self, + request: compute.InsertRolloutPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.InsertRolloutPlanRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for insert + + Override in a subclass to manipulate the request or metadata + before they are sent to the RolloutPlans server. + """ + return request, metadata + + def post_insert(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for insert + + DEPRECATED. Please use the `post_insert_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RolloutPlans server but before + it is returned to user code. This `post_insert` interceptor runs + before the `post_insert_with_metadata` interceptor. + """ + return response + + def post_insert_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RolloutPlans server but before it is returned to user code. + + We recommend only using this `post_insert_with_metadata` + interceptor in new development instead of the `post_insert` interceptor. + When both interceptors are used, this `post_insert_with_metadata` interceptor runs after the + `post_insert` interceptor. The (possibly modified) response returned by + `post_insert` will be passed to + `post_insert_with_metadata`. + """ + return response, metadata + + def pre_list( + self, + request: compute.ListRolloutPlansRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListRolloutPlansRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list + + Override in a subclass to manipulate the request or metadata + before they are sent to the RolloutPlans server. + """ + return request, metadata + + def post_list( + self, response: compute.RolloutPlansListResponse + ) -> compute.RolloutPlansListResponse: + """Post-rpc interceptor for list + + DEPRECATED. Please use the `post_list_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RolloutPlans server but before + it is returned to user code. This `post_list` interceptor runs + before the `post_list_with_metadata` interceptor. + """ + return response + + def post_list_with_metadata( + self, + response: compute.RolloutPlansListResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.RolloutPlansListResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RolloutPlans server but before it is returned to user code. + + We recommend only using this `post_list_with_metadata` + interceptor in new development instead of the `post_list` interceptor. + When both interceptors are used, this `post_list_with_metadata` interceptor runs after the + `post_list` interceptor. The (possibly modified) response returned by + `post_list` will be passed to + `post_list_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class RolloutPlansRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RolloutPlansRestInterceptor + + +class RolloutPlansRestTransport(_BaseRolloutPlansRestTransport): + """REST backend synchronous transport for RolloutPlans. + + The RolloutPlans API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[RolloutPlansRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[RolloutPlansRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RolloutPlansRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Delete(_BaseRolloutPlansRestTransport._BaseDelete, RolloutPlansRestStub): + def __hash__(self): + return hash("RolloutPlansRestTransport.Delete") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.DeleteRolloutPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteRolloutPlanRequest): + The request object. A request message for + RolloutPlans.Delete. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseRolloutPlansRestTransport._BaseDelete._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete(request, metadata) + transcoded_request = ( + _BaseRolloutPlansRestTransport._BaseDelete._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutPlansRestTransport._BaseDelete._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.RolloutPlansClient.Delete", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "rpcName": "Delete", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutPlansRestTransport._Delete._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.RolloutPlansClient.delete", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "rpcName": "Delete", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Get(_BaseRolloutPlansRestTransport._BaseGet, RolloutPlansRestStub): + def __hash__(self): + return hash("RolloutPlansRestTransport.Get") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetRolloutPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RolloutPlan: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetRolloutPlanRequest): + The request object. A request message for + RolloutPlans.Get. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.RolloutPlan: + RolloutPlan resource. + + A RolloutPlan is the customer-defined + strategy to divide a large-scale change + into smaller increments, referred to as + "waves". Each wave targets a specific + portion of the overall affected area and + defines criteria that must be met before + progressing to the subsequent wave. + + """ + + http_options = _BaseRolloutPlansRestTransport._BaseGet._get_http_options() + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseRolloutPlansRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutPlansRestTransport._BaseGet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.RolloutPlansClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutPlansRestTransport._Get._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.RolloutPlan() + pb_resp = compute.RolloutPlan.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.RolloutPlan.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.RolloutPlansClient.get", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Insert(_BaseRolloutPlansRestTransport._BaseInsert, RolloutPlansRestStub): + def __hash__(self): + return hash("RolloutPlansRestTransport.Insert") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.InsertRolloutPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertRolloutPlanRequest): + The request object. A request message for + RolloutPlans.Insert. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseRolloutPlansRestTransport._BaseInsert._get_http_options() + ) + + request, metadata = self._interceptor.pre_insert(request, metadata) + transcoded_request = ( + _BaseRolloutPlansRestTransport._BaseInsert._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseRolloutPlansRestTransport._BaseInsert._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutPlansRestTransport._BaseInsert._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.RolloutPlansClient.Insert", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "rpcName": "Insert", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutPlansRestTransport._Insert._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.RolloutPlansClient.insert", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "rpcName": "Insert", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List(_BaseRolloutPlansRestTransport._BaseList, RolloutPlansRestStub): + def __hash__(self): + return hash("RolloutPlansRestTransport.List") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.ListRolloutPlansRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RolloutPlansListResponse: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListRolloutPlansRequest): + The request object. A request message for + RolloutPlans.List. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.RolloutPlansListResponse: + Contains a list of RolloutPlan + resources. + + """ + + http_options = _BaseRolloutPlansRestTransport._BaseList._get_http_options() + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = ( + _BaseRolloutPlansRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutPlansRestTransport._BaseList._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.RolloutPlansClient.List", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutPlansRestTransport._List._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.RolloutPlansListResponse() + pb_resp = compute.RolloutPlansListResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.RolloutPlansListResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.RolloutPlansClient.list", + extra={ + "serviceName": "google.cloud.compute.v1.RolloutPlans", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete(self) -> Callable[[compute.DeleteRolloutPlanRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Delete(self._session, self._host, self._interceptor) # type: ignore + + @property + def get(self) -> Callable[[compute.GetRolloutPlanRequest], compute.RolloutPlan]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert(self) -> Callable[[compute.InsertRolloutPlanRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Insert(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[[compute.ListRolloutPlansRequest], compute.RolloutPlansListResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._List(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("RolloutPlansRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/rest_base.py new file mode 100644 index 000000000000..ce4538626529 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollout_plans/transports/rest_base.py @@ -0,0 +1,285 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO, RolloutPlansTransport + + +class _BaseRolloutPlansRestTransport(RolloutPlansTransport): + """Base REST backend transport for RolloutPlans. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseDelete: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/compute/v1/projects/{project}/global/rolloutPlans/{rollout_plan}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteRolloutPlanRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseRolloutPlansRestTransport._BaseDelete._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseGet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/global/rolloutPlans/{rollout_plan}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetRolloutPlanRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseRolloutPlansRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseInsert: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/global/rolloutPlans", + "body": "rollout_plan_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.InsertRolloutPlanRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseRolloutPlansRestTransport._BaseInsert._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/global/rolloutPlans", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListRolloutPlansRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseRolloutPlansRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseRolloutPlansRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/__init__.py new file mode 100644 index 000000000000..4c115c96cff2 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RolloutsClient + +__all__ = ("RolloutsClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/client.py new file mode 100644 index 000000000000..9a658ef00897 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/client.py @@ -0,0 +1,1514 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import functools +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation, gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.extended_operation as extended_operation # type: ignore + +from google.cloud.compute_v1.services.rollouts import pagers +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, RolloutsTransport +from .transports.rest import RolloutsRestTransport + + +class RolloutsClientMeta(type): + """Metaclass for the Rollouts client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[RolloutsTransport]] + _transport_registry["rest"] = RolloutsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RolloutsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RolloutsClient(metaclass=RolloutsClientMeta): + """The Rollouts API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RolloutsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RolloutsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RolloutsTransport: + """Returns the transport used by the client instance. + + Returns: + RolloutsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = RolloutsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = RolloutsClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = RolloutsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = RolloutsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RolloutsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RolloutsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, RolloutsTransport, Callable[..., RolloutsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the rollouts client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RolloutsTransport,Callable[..., RolloutsTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RolloutsTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + RolloutsClient._read_environment_variables() + ) + self._client_cert_source = RolloutsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RolloutsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, RolloutsTransport) + if transport_provided: + # transport is a RolloutsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(RolloutsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or RolloutsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[RolloutsTransport], Callable[..., RolloutsTransport] + ] = ( + RolloutsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RolloutsTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.compute_v1.RolloutsClient`.", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.compute.v1.Rollouts", + "credentialsType": None, + }, + ) + + def cancel_unary( + self, + request: Optional[Union[compute.CancelRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Cancels a Rollout. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_cancel(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.CancelRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.cancel(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CancelRolloutRequest, dict]): + The request object. A request message for + Rollouts.Cancel. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the Rollout resource to + cancel. + + This corresponds to the ``rollout`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CancelRolloutRequest): + request = compute.CancelRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def cancel( + self, + request: Optional[Union[compute.CancelRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Cancels a Rollout. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_cancel(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.CancelRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.cancel(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CancelRolloutRequest, dict]): + The request object. A request message for + Rollouts.Cancel. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the Rollout resource to + cancel. + + This corresponds to the ``rollout`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.CancelRolloutRequest): + request = compute.CancelRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def delete_unary( + self, + request: Optional[Union[compute.DeleteRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Deletes a Rollout. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteRolloutRequest, dict]): + The request object. A request message for + Rollouts.Delete. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the Rollout resource to + delete. + + This corresponds to the ``rollout`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.DeleteRolloutRequest): + request = compute.DeleteRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete( + self, + request: Optional[Union[compute.DeleteRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes a Rollout. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteRolloutRequest, dict]): + The request object. A request message for + Rollouts.Delete. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the Rollout resource to + delete. + + This corresponds to the ``rollout`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.DeleteRolloutRequest): + request = compute.DeleteRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def get( + self, + request: Optional[Union[compute.GetRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Rollout: + r"""Gets details of a single project-scoped Rollout. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.GetRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetRolloutRequest, dict]): + The request object. A request message for Rollouts.Get. + See the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the persistent rollout to + return. + + This corresponds to the ``rollout`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.types.Rollout: + Rollout resource. + + A Rollout is a specific instance of a + RolloutPlan. It represents a single + execution of a strategy to roll out a + specific resource. It also provides APIs + to interact with the rollout. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project, rollout] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetRolloutRequest): + request = compute.GetRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list( + self, + request: Optional[Union[compute.ListRolloutsRequest, dict]] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPager: + r"""Lists Rollouts in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_list(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.ListRolloutsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListRolloutsRequest, dict]): + The request object. A request message for Rollouts.List. + See the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1.services.rollouts.pagers.ListPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.ListRolloutsRequest): + request = compute.ListRolloutsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RolloutsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("RolloutsClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/pagers.py new file mode 100644 index 000000000000..62b519b5a3ee --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.compute_v1.types import compute + + +class ListPager: + """A pager for iterating through ``list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.RolloutsListResponse` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``List`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.RolloutsListResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., compute.RolloutsListResponse], + request: compute.ListRolloutsRequest, + response: compute.RolloutsListResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.compute_v1.types.ListRolloutsRequest): + The initial request object. + response (google.cloud.compute_v1.types.RolloutsListResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = compute.ListRolloutsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.RolloutsListResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[compute.Rollout]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/README.rst b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/README.rst new file mode 100644 index 000000000000..b5936eb0a6d1 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``RolloutsTransport`` is the ABC for all transports. + +- public child ``RolloutsGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``RolloutsGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseRolloutsRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``RolloutsRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/__init__.py new file mode 100644 index 000000000000..6bec3d08f780 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RolloutsTransport +from .rest import RolloutsRestInterceptor, RolloutsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RolloutsTransport]] +_transport_registry["rest"] = RolloutsRestTransport + +__all__ = ( + "RolloutsTransport", + "RolloutsRestTransport", + "RolloutsRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/base.py new file mode 100644 index 000000000000..d3f70163e219 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/base.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.services import global_operations +from google.cloud.compute_v1.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class RolloutsTransport(abc.ABC): + """Abstract transport class for Rollouts.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + self._extended_operations_services: Dict[str, Any] = {} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.cancel: gapic_v1.method.wrap_method( + self.cancel, + default_timeout=600.0, + client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=600.0, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def cancel( + self, + ) -> Callable[ + [compute.CancelRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetRolloutRequest], Union[compute.Rollout, Awaitable[compute.Rollout]] + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListRolloutsRequest], + Union[compute.RolloutsListResponse, Awaitable[compute.RolloutsListResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _global_operations_client(self) -> global_operations.GlobalOperationsClient: + ex_op_service = self._extended_operations_services.get("global_operations") + if not ex_op_service: + ex_op_service = global_operations.GlobalOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["global_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("RolloutsTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest.py new file mode 100644 index 000000000000..d03f3eb6558b --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest.py @@ -0,0 +1,1060 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseRolloutsRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class RolloutsRestInterceptor: + """Interceptor for Rollouts. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RolloutsRestTransport. + + .. code-block:: python + class MyCustomRolloutsInterceptor(RolloutsRestInterceptor): + def pre_cancel(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_cancel(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RolloutsRestTransport(interceptor=MyCustomRolloutsInterceptor()) + client = RolloutsClient(transport=transport) + + + """ + + def pre_cancel( + self, + request: compute.CancelRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.CancelRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_cancel(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for cancel + + DEPRECATED. Please use the `post_cancel_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_cancel` interceptor runs + before the `post_cancel_with_metadata` interceptor. + """ + return response + + def post_cancel_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for cancel + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_cancel_with_metadata` + interceptor in new development instead of the `post_cancel` interceptor. + When both interceptors are used, this `post_cancel_with_metadata` interceptor runs after the + `post_cancel` interceptor. The (possibly modified) response returned by + `post_cancel` will be passed to + `post_cancel_with_metadata`. + """ + return response, metadata + + def pre_delete( + self, + request: compute.DeleteRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.DeleteRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_delete(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete + + DEPRECATED. Please use the `post_delete_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_delete` interceptor runs + before the `post_delete_with_metadata` interceptor. + """ + return response + + def post_delete_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_delete_with_metadata` + interceptor in new development instead of the `post_delete` interceptor. + When both interceptors are used, this `post_delete_with_metadata` interceptor runs after the + `post_delete` interceptor. The (possibly modified) response returned by + `post_delete` will be passed to + `post_delete_with_metadata`. + """ + return response, metadata + + def pre_get( + self, + request: compute.GetRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.GetRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_get(self, response: compute.Rollout) -> compute.Rollout: + """Post-rpc interceptor for get + + DEPRECATED. Please use the `post_get_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_get` interceptor runs + before the `post_get_with_metadata` interceptor. + """ + return response + + def post_get_with_metadata( + self, + response: compute.Rollout, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Rollout, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_get_with_metadata` + interceptor in new development instead of the `post_get` interceptor. + When both interceptors are used, this `post_get_with_metadata` interceptor runs after the + `post_get` interceptor. The (possibly modified) response returned by + `post_get` will be passed to + `post_get_with_metadata`. + """ + return response, metadata + + def pre_list( + self, + request: compute.ListRolloutsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ListRolloutsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_list( + self, response: compute.RolloutsListResponse + ) -> compute.RolloutsListResponse: + """Post-rpc interceptor for list + + DEPRECATED. Please use the `post_list_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_list` interceptor runs + before the `post_list_with_metadata` interceptor. + """ + return response + + def post_list_with_metadata( + self, + response: compute.RolloutsListResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.RolloutsListResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_list_with_metadata` + interceptor in new development instead of the `post_list` interceptor. + When both interceptors are used, this `post_list_with_metadata` interceptor runs after the + `post_list` interceptor. The (possibly modified) response returned by + `post_list` will be passed to + `post_list_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class RolloutsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RolloutsRestInterceptor + + +class RolloutsRestTransport(_BaseRolloutsRestTransport): + """REST backend synchronous transport for Rollouts. + + The Rollouts API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[RolloutsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[RolloutsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RolloutsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Cancel(_BaseRolloutsRestTransport._BaseCancel, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Cancel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.CancelRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the cancel method over HTTP. + + Args: + request (~.compute.CancelRolloutRequest): + The request object. A request message for + Rollouts.Cancel. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRolloutsRestTransport._BaseCancel._get_http_options() + + request, metadata = self._interceptor.pre_cancel(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BaseCancel._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutsRestTransport._BaseCancel._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.RolloutsClient.Cancel", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Cancel", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Cancel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_cancel(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_cancel_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.RolloutsClient.cancel", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Cancel", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Delete(_BaseRolloutsRestTransport._BaseDelete, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Delete") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.DeleteRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteRolloutRequest): + The request object. A request message for + Rollouts.Delete. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRolloutsRestTransport._BaseDelete._get_http_options() + + request, metadata = self._interceptor.pre_delete(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BaseDelete._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutsRestTransport._BaseDelete._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.RolloutsClient.Delete", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Delete", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Delete._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.RolloutsClient.delete", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Delete", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Get(_BaseRolloutsRestTransport._BaseGet, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Get") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Rollout: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetRolloutRequest): + The request object. A request message for Rollouts.Get. + See the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Rollout: + Rollout resource. + + A Rollout is a specific instance of a + RolloutPlan. It represents a single + execution of a strategy to roll out a + specific resource. It also provides APIs + to interact with the rollout. + + """ + + http_options = _BaseRolloutsRestTransport._BaseGet._get_http_options() + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseRolloutsRestTransport._BaseGet._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.RolloutsClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Get._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Rollout() + pb_resp = compute.Rollout.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Rollout.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.RolloutsClient.get", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List(_BaseRolloutsRestTransport._BaseList, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.List") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.ListRolloutsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RolloutsListResponse: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListRolloutsRequest): + The request object. A request message for Rollouts.List. + See the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.RolloutsListResponse: + + """ + + http_options = _BaseRolloutsRestTransport._BaseList._get_http_options() + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseRolloutsRestTransport._BaseList._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.RolloutsClient.List", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._List._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.RolloutsListResponse() + pb_resp = compute.RolloutsListResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.RolloutsListResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.RolloutsClient.list", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def cancel(self) -> Callable[[compute.CancelRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Cancel(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete(self) -> Callable[[compute.DeleteRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Delete(self._session, self._host, self._interceptor) # type: ignore + + @property + def get(self) -> Callable[[compute.GetRolloutRequest], compute.Rollout]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[[compute.ListRolloutsRequest], compute.RolloutsListResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._List(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("RolloutsRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest_base.py new file mode 100644 index 000000000000..7594c13936e1 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest_base.py @@ -0,0 +1,275 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO, RolloutsTransport + + +class _BaseRolloutsRestTransport(RolloutsTransport): + """Base REST backend transport for Rollouts. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCancel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/compute/v1/projects/{project}/global/rollouts/{rollout}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.CancelRolloutRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseRolloutsRestTransport._BaseCancel._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseDelete: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/compute/v1/projects/{project}/global/rollouts/{rollout}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteRolloutRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseRolloutsRestTransport._BaseDelete._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseGet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/global/rollouts/{rollout}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetRolloutRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseRolloutsRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/global/rollouts", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListRolloutsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseRolloutsRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseRolloutsRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_vm_extension_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_vm_extension_policies/client.py index 76a1169e8f7d..1a944b412f85 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_vm_extension_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_vm_extension_policies/client.py @@ -729,7 +729,8 @@ def delete_unary( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.Operation: - r"""Deletes a specified zone VM extension policy. + r"""Deletes a specified zone VM extension policy within a + project. .. code-block:: python @@ -864,7 +865,8 @@ def delete( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> extended_operation.ExtendedOperation: - r"""Deletes a specified zone VM extension policy. + r"""Deletes a specified zone VM extension policy within a + project. .. code-block:: python @@ -1023,7 +1025,7 @@ def get( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.VmExtensionPolicy: r"""Retrieves details of a specific zone VM extension - policy. + policy within a project. .. code-block:: python @@ -1583,7 +1585,8 @@ def update_unary( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.Operation: - r"""Modifies an existing zone VM extension policy. + r"""Modifies an existing zone VM extension policy within + a project. .. code-block:: python @@ -1731,7 +1734,8 @@ def update( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> extended_operation.ExtendedOperation: - r"""Modifies an existing zone VM extension policy. + r"""Modifies an existing zone VM extension policy within + a project. .. code-block:: python diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py index b159608136c1..75aab92f650e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py @@ -64,6 +64,7 @@ AggregatedListForwardingRulesRequest, AggregatedListFutureReservationsRequest, AggregatedListGlobalOperationsRequest, + AggregatedListGlobalVmExtensionPoliciesRequest, AggregatedListHealthChecksRequest, AggregatedListInstanceGroupManagersRequest, AggregatedListInstanceGroupsRequest, @@ -216,6 +217,8 @@ CancelFutureReservationRequest, CancelInstanceGroupManagerResizeRequestRequest, CancelRegionInstanceGroupManagerResizeRequestRequest, + CancelRequestRemovePeeringNetworkRequest, + CancelRolloutRequest, CircuitBreakers, CloneRulesFirewallPolicyRequest, CloneRulesNetworkFirewallPolicyRequest, @@ -271,6 +274,7 @@ DeleteGlobalOrganizationOperationRequest, DeleteGlobalOrganizationOperationResponse, DeleteGlobalPublicDelegatedPrefixeRequest, + DeleteGlobalVmExtensionPolicyRequest, DeleteHealthCheckRequest, DeleteImageRequest, DeleteInstanceGroupManagerRequest, @@ -332,6 +336,8 @@ DeleteRegionUrlMapRequest, DeleteReservationRequest, DeleteResourcePolicyRequest, + DeleteRolloutPlanRequest, + DeleteRolloutRequest, DeleteRoutePolicyRouterRequest, DeleteRouteRequest, DeleteRouterRequest, @@ -481,6 +487,7 @@ GetGlobalOperationRequest, GetGlobalOrganizationOperationRequest, GetGlobalPublicDelegatedPrefixeRequest, + GetGlobalVmExtensionPolicyRequest, GetGuestAttributesInstanceRequest, GetHealthBackendServiceRequest, GetHealthCheckRequest, @@ -499,6 +506,7 @@ GetIamPolicyInstantSnapshotRequest, GetIamPolicyInterconnectAttachmentGroupRequest, GetIamPolicyInterconnectGroupRequest, + GetIamPolicyLicenseCodeRequest, GetIamPolicyLicenseRequest, GetIamPolicyMachineImageRequest, GetIamPolicyNetworkAttachmentRequest, @@ -597,6 +605,8 @@ GetReservationSlotRequest, GetReservationSubBlockRequest, GetResourcePolicyRequest, + GetRolloutPlanRequest, + GetRolloutRequest, GetRoutePolicyRouterRequest, GetRouteRequest, GetRouterRequest, @@ -647,6 +657,16 @@ GlobalOrganizationSetPolicyRequest, GlobalSetLabelsRequest, GlobalSetPolicyRequest, + GlobalVmExtensionPolicy, + GlobalVmExtensionPolicyExtensionPolicy, + GlobalVmExtensionPolicyInstanceSelector, + GlobalVmExtensionPolicyLabelSelector, + GlobalVmExtensionPolicyList, + GlobalVmExtensionPolicyRolloutOperation, + GlobalVmExtensionPolicyRolloutOperationRolloutInput, + GlobalVmExtensionPolicyRolloutOperationRolloutStatus, + GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata, + GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus, GroupMaintenanceInfo, GRPCHealthCheck, GRPCTLSHealthCheck, @@ -716,6 +736,7 @@ InsertGlobalForwardingRuleRequest, InsertGlobalNetworkEndpointGroupRequest, InsertGlobalPublicDelegatedPrefixeRequest, + InsertGlobalVmExtensionPolicyRequest, InsertHealthCheckRequest, InsertImageRequest, InsertInstanceGroupManagerRequest, @@ -770,6 +791,7 @@ InsertRegionUrlMapRequest, InsertReservationRequest, InsertResourcePolicyRequest, + InsertRolloutPlanRequest, InsertRouteRequest, InsertRouterRequest, InsertSecurityPolicyRequest, @@ -1008,6 +1030,7 @@ ListGlobalOperationsRequest, ListGlobalOrganizationOperationsRequest, ListGlobalPublicDelegatedPrefixesRequest, + ListGlobalVmExtensionPoliciesRequest, ListHealthChecksRequest, ListImagesRequest, ListInstanceGroupManagerResizeRequestsRequest, @@ -1090,6 +1113,8 @@ ListReservationsRequest, ListReservationSubBlocksRequest, ListResourcePoliciesRequest, + ListRolloutPlansRequest, + ListRolloutsRequest, ListRoutePoliciesRoutersRequest, ListRoutersRequest, ListRoutesRequest, @@ -1194,6 +1219,7 @@ NetworkProfilesListResponse, NetworkRoutingConfig, NetworksAddPeeringRequest, + NetworksCancelRequestRemovePeeringRequest, NetworksGetEffectiveFirewallsResponse, NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy, NetworksRemovePeeringRequest, @@ -1479,6 +1505,23 @@ ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, ResumeInstancesRegionInstanceGroupManagerRequest, + Rollout, + RolloutPlan, + RolloutPlansListResponse, + RolloutPlanWave, + RolloutPlanWaveOrchestrationOptions, + RolloutPlanWaveOrchestrationOptionsDelay, + RolloutPlanWaveSelector, + RolloutPlanWaveSelectorLocationSelector, + RolloutPlanWaveSelectorResourceHierarchySelector, + RolloutPlanWaveValidation, + RolloutPlanWaveValidationTimeBasedValidationMetadata, + RolloutRolloutEntity, + RolloutRolloutEntityOrchestratedEntity, + RolloutsListResponse, + RolloutWaveDetails, + RolloutWaveDetailsOrchestratedWaveDetails, + RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus, Route, RouteAsPath, RouteList, @@ -1589,6 +1632,7 @@ SetIamPolicyInstantSnapshotRequest, SetIamPolicyInterconnectAttachmentGroupRequest, SetIamPolicyInterconnectGroupRequest, + SetIamPolicyLicenseCodeRequest, SetIamPolicyLicenseRequest, SetIamPolicyMachineImageRequest, SetIamPolicyNetworkAttachmentRequest, @@ -1868,6 +1912,7 @@ UpdateDisplayDeviceInstanceRequest, UpdateFirewallRequest, UpdateFutureReservationRequest, + UpdateGlobalVmExtensionPolicyRequest, UpdateHealthCheckRequest, UpdateInstanceRequest, UpdateKmsKeyDiskRequest, @@ -1915,7 +1960,9 @@ VmEndpointNatMappingsInterfaceNatMappings, VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings, VmEndpointNatMappingsList, + VmExtensionPoliciesScopedList, VmExtensionPolicy, + VmExtensionPolicyAggregatedListResponse, VmExtensionPolicyExtensionPolicy, VmExtensionPolicyInstanceSelector, VmExtensionPolicyLabelSelector, @@ -2019,6 +2066,7 @@ "AggregatedListForwardingRulesRequest", "AggregatedListFutureReservationsRequest", "AggregatedListGlobalOperationsRequest", + "AggregatedListGlobalVmExtensionPoliciesRequest", "AggregatedListHealthChecksRequest", "AggregatedListInstanceGroupManagersRequest", "AggregatedListInstanceGroupsRequest", @@ -2171,6 +2219,8 @@ "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", "CancelRegionInstanceGroupManagerResizeRequestRequest", + "CancelRequestRemovePeeringNetworkRequest", + "CancelRolloutRequest", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -2226,6 +2276,7 @@ "DeleteGlobalOrganizationOperationRequest", "DeleteGlobalOrganizationOperationResponse", "DeleteGlobalPublicDelegatedPrefixeRequest", + "DeleteGlobalVmExtensionPolicyRequest", "DeleteHealthCheckRequest", "DeleteImageRequest", "DeleteInstanceGroupManagerRequest", @@ -2287,6 +2338,8 @@ "DeleteRegionUrlMapRequest", "DeleteReservationRequest", "DeleteResourcePolicyRequest", + "DeleteRolloutPlanRequest", + "DeleteRolloutRequest", "DeleteRoutePolicyRouterRequest", "DeleteRouteRequest", "DeleteRouterRequest", @@ -2436,6 +2489,7 @@ "GetGlobalOperationRequest", "GetGlobalOrganizationOperationRequest", "GetGlobalPublicDelegatedPrefixeRequest", + "GetGlobalVmExtensionPolicyRequest", "GetGuestAttributesInstanceRequest", "GetHealthBackendServiceRequest", "GetHealthCheckRequest", @@ -2454,6 +2508,7 @@ "GetIamPolicyInstantSnapshotRequest", "GetIamPolicyInterconnectAttachmentGroupRequest", "GetIamPolicyInterconnectGroupRequest", + "GetIamPolicyLicenseCodeRequest", "GetIamPolicyLicenseRequest", "GetIamPolicyMachineImageRequest", "GetIamPolicyNetworkAttachmentRequest", @@ -2552,6 +2607,8 @@ "GetReservationSlotRequest", "GetReservationSubBlockRequest", "GetResourcePolicyRequest", + "GetRolloutPlanRequest", + "GetRolloutRequest", "GetRoutePolicyRouterRequest", "GetRouteRequest", "GetRouterRequest", @@ -2602,6 +2659,16 @@ "GlobalOrganizationSetPolicyRequest", "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", + "GlobalVmExtensionPolicy", + "GlobalVmExtensionPolicyExtensionPolicy", + "GlobalVmExtensionPolicyInstanceSelector", + "GlobalVmExtensionPolicyLabelSelector", + "GlobalVmExtensionPolicyList", + "GlobalVmExtensionPolicyRolloutOperation", + "GlobalVmExtensionPolicyRolloutOperationRolloutInput", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatus", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus", "GroupMaintenanceInfo", "GRPCHealthCheck", "GRPCTLSHealthCheck", @@ -2671,6 +2738,7 @@ "InsertGlobalForwardingRuleRequest", "InsertGlobalNetworkEndpointGroupRequest", "InsertGlobalPublicDelegatedPrefixeRequest", + "InsertGlobalVmExtensionPolicyRequest", "InsertHealthCheckRequest", "InsertImageRequest", "InsertInstanceGroupManagerRequest", @@ -2725,6 +2793,7 @@ "InsertRegionUrlMapRequest", "InsertReservationRequest", "InsertResourcePolicyRequest", + "InsertRolloutPlanRequest", "InsertRouteRequest", "InsertRouterRequest", "InsertSecurityPolicyRequest", @@ -2963,6 +3032,7 @@ "ListGlobalOperationsRequest", "ListGlobalOrganizationOperationsRequest", "ListGlobalPublicDelegatedPrefixesRequest", + "ListGlobalVmExtensionPoliciesRequest", "ListHealthChecksRequest", "ListImagesRequest", "ListInstanceGroupManagerResizeRequestsRequest", @@ -3045,6 +3115,8 @@ "ListReservationsRequest", "ListReservationSubBlocksRequest", "ListResourcePoliciesRequest", + "ListRolloutPlansRequest", + "ListRolloutsRequest", "ListRoutePoliciesRoutersRequest", "ListRoutersRequest", "ListRoutesRequest", @@ -3149,6 +3221,7 @@ "NetworkProfilesListResponse", "NetworkRoutingConfig", "NetworksAddPeeringRequest", + "NetworksCancelRequestRemovePeeringRequest", "NetworksGetEffectiveFirewallsResponse", "NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "NetworksRemovePeeringRequest", @@ -3434,6 +3507,23 @@ "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "Rollout", + "RolloutPlan", + "RolloutPlansListResponse", + "RolloutPlanWave", + "RolloutPlanWaveOrchestrationOptions", + "RolloutPlanWaveOrchestrationOptionsDelay", + "RolloutPlanWaveSelector", + "RolloutPlanWaveSelectorLocationSelector", + "RolloutPlanWaveSelectorResourceHierarchySelector", + "RolloutPlanWaveValidation", + "RolloutPlanWaveValidationTimeBasedValidationMetadata", + "RolloutRolloutEntity", + "RolloutRolloutEntityOrchestratedEntity", + "RolloutsListResponse", + "RolloutWaveDetails", + "RolloutWaveDetailsOrchestratedWaveDetails", + "RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus", "Route", "RouteAsPath", "RouteList", @@ -3544,6 +3634,7 @@ "SetIamPolicyInstantSnapshotRequest", "SetIamPolicyInterconnectAttachmentGroupRequest", "SetIamPolicyInterconnectGroupRequest", + "SetIamPolicyLicenseCodeRequest", "SetIamPolicyLicenseRequest", "SetIamPolicyMachineImageRequest", "SetIamPolicyNetworkAttachmentRequest", @@ -3823,6 +3914,7 @@ "UpdateDisplayDeviceInstanceRequest", "UpdateFirewallRequest", "UpdateFutureReservationRequest", + "UpdateGlobalVmExtensionPolicyRequest", "UpdateHealthCheckRequest", "UpdateInstanceRequest", "UpdateKmsKeyDiskRequest", @@ -3870,7 +3962,9 @@ "VmEndpointNatMappingsInterfaceNatMappings", "VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings", "VmEndpointNatMappingsList", + "VmExtensionPoliciesScopedList", "VmExtensionPolicy", + "VmExtensionPolicyAggregatedListResponse", "VmExtensionPolicyExtensionPolicy", "VmExtensionPolicyInstanceSelector", "VmExtensionPolicyLabelSelector", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py index 6e503fcaf6e0..e0e92518bf03 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py @@ -74,6 +74,7 @@ "AggregatedListForwardingRulesRequest", "AggregatedListFutureReservationsRequest", "AggregatedListGlobalOperationsRequest", + "AggregatedListGlobalVmExtensionPoliciesRequest", "AggregatedListHealthChecksRequest", "AggregatedListInstanceGroupManagersRequest", "AggregatedListInstanceGroupsRequest", @@ -225,6 +226,8 @@ "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", "CancelRegionInstanceGroupManagerResizeRequestRequest", + "CancelRequestRemovePeeringNetworkRequest", + "CancelRolloutRequest", "CircuitBreakers", "CloneRulesFirewallPolicyRequest", "CloneRulesNetworkFirewallPolicyRequest", @@ -280,6 +283,7 @@ "DeleteGlobalOrganizationOperationRequest", "DeleteGlobalOrganizationOperationResponse", "DeleteGlobalPublicDelegatedPrefixeRequest", + "DeleteGlobalVmExtensionPolicyRequest", "DeleteHealthCheckRequest", "DeleteImageRequest", "DeleteInstanceGroupManagerRequest", @@ -341,6 +345,8 @@ "DeleteRegionUrlMapRequest", "DeleteReservationRequest", "DeleteResourcePolicyRequest", + "DeleteRolloutPlanRequest", + "DeleteRolloutRequest", "DeleteRoutePolicyRouterRequest", "DeleteRouteRequest", "DeleteRouterRequest", @@ -492,6 +498,7 @@ "GetGlobalOperationRequest", "GetGlobalOrganizationOperationRequest", "GetGlobalPublicDelegatedPrefixeRequest", + "GetGlobalVmExtensionPolicyRequest", "GetGuestAttributesInstanceRequest", "GetHealthBackendServiceRequest", "GetHealthCheckRequest", @@ -510,6 +517,7 @@ "GetIamPolicyInstantSnapshotRequest", "GetIamPolicyInterconnectAttachmentGroupRequest", "GetIamPolicyInterconnectGroupRequest", + "GetIamPolicyLicenseCodeRequest", "GetIamPolicyLicenseRequest", "GetIamPolicyMachineImageRequest", "GetIamPolicyNetworkAttachmentRequest", @@ -608,6 +616,8 @@ "GetReservationSlotRequest", "GetReservationSubBlockRequest", "GetResourcePolicyRequest", + "GetRolloutPlanRequest", + "GetRolloutRequest", "GetRoutePolicyRouterRequest", "GetRouteRequest", "GetRouterRequest", @@ -658,6 +668,16 @@ "GlobalOrganizationSetPolicyRequest", "GlobalSetLabelsRequest", "GlobalSetPolicyRequest", + "GlobalVmExtensionPolicy", + "GlobalVmExtensionPolicyExtensionPolicy", + "GlobalVmExtensionPolicyInstanceSelector", + "GlobalVmExtensionPolicyLabelSelector", + "GlobalVmExtensionPolicyList", + "GlobalVmExtensionPolicyRolloutOperation", + "GlobalVmExtensionPolicyRolloutOperationRolloutInput", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatus", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata", + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus", "GroupMaintenanceInfo", "GuestAttributes", "GuestAttributesEntry", @@ -725,6 +745,7 @@ "InsertGlobalForwardingRuleRequest", "InsertGlobalNetworkEndpointGroupRequest", "InsertGlobalPublicDelegatedPrefixeRequest", + "InsertGlobalVmExtensionPolicyRequest", "InsertHealthCheckRequest", "InsertImageRequest", "InsertInstanceGroupManagerRequest", @@ -779,6 +800,7 @@ "InsertRegionUrlMapRequest", "InsertReservationRequest", "InsertResourcePolicyRequest", + "InsertRolloutPlanRequest", "InsertRouteRequest", "InsertRouterRequest", "InsertSecurityPolicyRequest", @@ -1017,6 +1039,7 @@ "ListGlobalOperationsRequest", "ListGlobalOrganizationOperationsRequest", "ListGlobalPublicDelegatedPrefixesRequest", + "ListGlobalVmExtensionPoliciesRequest", "ListHealthChecksRequest", "ListImagesRequest", "ListInstanceGroupManagerResizeRequestsRequest", @@ -1099,6 +1122,8 @@ "ListReservationSubBlocksRequest", "ListReservationsRequest", "ListResourcePoliciesRequest", + "ListRolloutPlansRequest", + "ListRolloutsRequest", "ListRoutePoliciesRoutersRequest", "ListRoutersRequest", "ListRoutesRequest", @@ -1203,6 +1228,7 @@ "NetworkProfilesListResponse", "NetworkRoutingConfig", "NetworksAddPeeringRequest", + "NetworksCancelRequestRemovePeeringRequest", "NetworksGetEffectiveFirewallsResponse", "NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "NetworksRemovePeeringRequest", @@ -1488,6 +1514,23 @@ "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "Rollout", + "RolloutPlan", + "RolloutPlanWave", + "RolloutPlanWaveOrchestrationOptions", + "RolloutPlanWaveOrchestrationOptionsDelay", + "RolloutPlanWaveSelector", + "RolloutPlanWaveSelectorLocationSelector", + "RolloutPlanWaveSelectorResourceHierarchySelector", + "RolloutPlanWaveValidation", + "RolloutPlanWaveValidationTimeBasedValidationMetadata", + "RolloutPlansListResponse", + "RolloutRolloutEntity", + "RolloutRolloutEntityOrchestratedEntity", + "RolloutWaveDetails", + "RolloutWaveDetailsOrchestratedWaveDetails", + "RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus", + "RolloutsListResponse", "Route", "RouteAsPath", "RouteList", @@ -1599,6 +1642,7 @@ "SetIamPolicyInstantSnapshotRequest", "SetIamPolicyInterconnectAttachmentGroupRequest", "SetIamPolicyInterconnectGroupRequest", + "SetIamPolicyLicenseCodeRequest", "SetIamPolicyLicenseRequest", "SetIamPolicyMachineImageRequest", "SetIamPolicyNetworkAttachmentRequest", @@ -1877,6 +1921,7 @@ "UpdateDisplayDeviceInstanceRequest", "UpdateFirewallRequest", "UpdateFutureReservationRequest", + "UpdateGlobalVmExtensionPolicyRequest", "UpdateHealthCheckRequest", "UpdateInstanceRequest", "UpdateKmsKeyDiskRequest", @@ -1924,7 +1969,9 @@ "VmEndpointNatMappingsInterfaceNatMappings", "VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings", "VmEndpointNatMappingsList", + "VmExtensionPoliciesScopedList", "VmExtensionPolicy", + "VmExtensionPolicyAggregatedListResponse", "VmExtensionPolicyExtensionPolicy", "VmExtensionPolicyInstanceSelector", "VmExtensionPolicyLabelSelector", @@ -7024,9 +7071,10 @@ class AggregatedListGlobalOperationsRequest(proto.Message): ) -class AggregatedListHealthChecksRequest(proto.Message): - r"""A request message for HealthChecks.AggregatedList. See the - method description for details. +class AggregatedListGlobalVmExtensionPoliciesRequest(proto.Message): + r"""A request message for + GlobalVmExtensionPolicies.AggregatedList. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -7210,194 +7258,8 @@ class AggregatedListHealthChecksRequest(proto.Message): ) -class AggregatedListInstanceGroupManagersRequest(proto.Message): - r"""A request message for InstanceGroupManagers.AggregatedList. - See the method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - filter (str): - A filter expression that filters resources listed in the - response. Most Compute resources support two types of filter - expressions: expressions that support regular expressions - and expressions that follow API improvement proposal - AIP-160. These two types of filter expressions cannot be - mixed in one request. - - If you want to use AIP-160, your expression must specify the - field name, an operator, and the value that you want to use - for filtering. The value must be a string, a number, or a - boolean. The operator must be either ``=``, ``!=``, ``>``, - ``<``, ``<=``, ``>=`` or ``:``. - - For example, if you are filtering Compute Engine instances, - you can exclude instances named ``example-instance`` by - specifying ``name != example-instance``. - - The ``:*`` comparison can be used to test whether a key has - been defined. For example, to find all objects with - ``owner`` label use: - - :: - - labels.owner:* - - You can also filter nested fields. For example, you could - specify ``scheduling.automaticRestart = false`` to include - instances only if they are not scheduled for automatic - restarts. You can use filtering on nested fields to filter - based onresource labels. - - To filter on multiple expressions, provide each separate - expression within parentheses. For example: - - :: - - (scheduling.automaticRestart = true) - (cpuPlatform = "Intel Skylake") - - By default, each expression is an ``AND`` expression. - However, you can include ``AND`` and ``OR`` expressions - explicitly. For example: - - :: - - (cpuPlatform = "Intel Skylake") OR - (cpuPlatform = "Intel Broadwell") AND - (scheduling.automaticRestart = true) - - If you want to use a regular expression, use the ``eq`` - (equal) or ``ne`` (not equal) operator against a single - un-parenthesized expression with or without quotes or - against multiple parenthesized expressions. Examples: - - ``fieldname eq unquoted literal`` - ``fieldname eq 'single quoted literal'`` - ``fieldname eq "double quoted literal"`` - ``(fieldname1 eq literal) (fieldname2 ne "literal")`` - - The literal value is interpreted as a regular expression - using GoogleRE2 library syntax. The literal value must match - the entire field. - - For example, to filter for instances that do not end with - name "instance", you would use ``name ne .*instance``. - - You cannot combine constraints on multiple fields using - regular expressions. - - This field is a member of `oneof`_ ``_filter``. - include_all_scopes (bool): - Indicates whether every visible scope for - each scope type (zone, region, global) should be - included in the response. For new resource types - added after this field, the flag has no effect - as new resource types will always include every - visible scope for each scope type in response. - For resource types which predate this field, if - this flag is omitted or false, only scopes of - the scope types where the resource type is - expected to be found will be included. - - This field is a member of `oneof`_ ``_include_all_scopes``. - max_results (int): - The maximum number of results per page that should be - returned. If the number of available results is larger than - ``maxResults``, Compute Engine returns a ``nextPageToken`` - that can be used to get the next page of results in - subsequent list requests. Acceptable values are ``0`` to - ``500``, inclusive. (Default: ``500``) - - This field is a member of `oneof`_ ``_max_results``. - order_by (str): - Sorts list results by a certain order. By default, results - are returned in alphanumerical order based on the resource - name. - - You can also sort results in descending order based on the - creation timestamp using - ``orderBy="creationTimestamp desc"``. This sorts results - based on the ``creationTimestamp`` field in reverse - chronological order (newest result first). Use this to sort - resources like operations so that the newest operation is - returned first. - - Currently, only sorting by ``name`` or - ``creationTimestamp desc`` is supported. - - This field is a member of `oneof`_ ``_order_by``. - page_token (str): - Specifies a page token to use. Set ``pageToken`` to the - ``nextPageToken`` returned by a previous list request to get - the next page of results. - - This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. - return_partial_success (bool): - Opt-in for partial success behavior which - provides partial results in case of failure. The - default value is false. - - For example, when partial success behavior is - enabled, aggregatedList for a single zone scope - either returns all resources in the zone or no - resources, with an error code. - - This field is a member of `oneof`_ ``_return_partial_success``. - service_project_number (int): - The Shared VPC service project id or service - project number for which aggregated list request - is invoked for subnetworks list-usable api. - - This field is a member of `oneof`_ ``_service_project_number``. - """ - - filter: str = proto.Field( - proto.STRING, - number=336120696, - optional=True, - ) - include_all_scopes: bool = proto.Field( - proto.BOOL, - number=391327988, - optional=True, - ) - max_results: int = proto.Field( - proto.UINT32, - number=54715419, - optional=True, - ) - order_by: str = proto.Field( - proto.STRING, - number=160562920, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=19994697, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, - optional=True, - ) - service_project_number: int = proto.Field( - proto.INT64, - number=316757497, - optional=True, - ) - - -class AggregatedListInstanceGroupsRequest(proto.Message): - r"""A request message for InstanceGroups.AggregatedList. See the +class AggregatedListHealthChecksRequest(proto.Message): + r"""A request message for HealthChecks.AggregatedList. See the method description for details. @@ -7521,7 +7383,7 @@ class AggregatedListInstanceGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -7582,9 +7444,9 @@ class AggregatedListInstanceGroupsRequest(proto.Message): ) -class AggregatedListInstanceTemplatesRequest(proto.Message): - r"""A request message for InstanceTemplates.AggregatedList. See - the method description for details. +class AggregatedListInstanceGroupManagersRequest(proto.Message): + r"""A request message for InstanceGroupManagers.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -7707,7 +7569,7 @@ class AggregatedListInstanceTemplatesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -7768,8 +7630,8 @@ class AggregatedListInstanceTemplatesRequest(proto.Message): ) -class AggregatedListInstancesRequest(proto.Message): - r"""A request message for Instances.AggregatedList. See the +class AggregatedListInstanceGroupsRequest(proto.Message): + r"""A request message for InstanceGroups.AggregatedList. See the method description for details. @@ -7954,8 +7816,8 @@ class AggregatedListInstancesRequest(proto.Message): ) -class AggregatedListInstantSnapshotsRequest(proto.Message): - r"""A request message for InstantSnapshots.AggregatedList. See +class AggregatedListInstanceTemplatesRequest(proto.Message): + r"""A request message for InstanceTemplates.AggregatedList. See the method description for details. @@ -8079,7 +7941,7 @@ class AggregatedListInstantSnapshotsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -8140,9 +8002,9 @@ class AggregatedListInstantSnapshotsRequest(proto.Message): ) -class AggregatedListInterconnectAttachmentsRequest(proto.Message): - r"""A request message for InterconnectAttachments.AggregatedList. - See the method description for details. +class AggregatedListInstancesRequest(proto.Message): + r"""A request message for Instances.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -8326,9 +8188,9 @@ class AggregatedListInterconnectAttachmentsRequest(proto.Message): ) -class AggregatedListMachineTypesRequest(proto.Message): - r"""A request message for MachineTypes.AggregatedList. See the - method description for details. +class AggregatedListInstantSnapshotsRequest(proto.Message): + r"""A request message for InstantSnapshots.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -8512,9 +8374,9 @@ class AggregatedListMachineTypesRequest(proto.Message): ) -class AggregatedListNetworkAttachmentsRequest(proto.Message): - r"""A request message for NetworkAttachments.AggregatedList. See - the method description for details. +class AggregatedListInterconnectAttachmentsRequest(proto.Message): + r"""A request message for InterconnectAttachments.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -8698,10 +8560,9 @@ class AggregatedListNetworkAttachmentsRequest(proto.Message): ) -class AggregatedListNetworkEdgeSecurityServicesRequest(proto.Message): - r"""A request message for - NetworkEdgeSecurityServices.AggregatedList. See the method - description for details. +class AggregatedListMachineTypesRequest(proto.Message): + r"""A request message for MachineTypes.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -8824,7 +8685,7 @@ class AggregatedListNetworkEdgeSecurityServicesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -8885,9 +8746,9 @@ class AggregatedListNetworkEdgeSecurityServicesRequest(proto.Message): ) -class AggregatedListNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for NetworkEndpointGroups.AggregatedList. - See the method description for details. +class AggregatedListNetworkAttachmentsRequest(proto.Message): + r"""A request message for NetworkAttachments.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -9071,9 +8932,10 @@ class AggregatedListNetworkEndpointGroupsRequest(proto.Message): ) -class AggregatedListNetworkFirewallPoliciesRequest(proto.Message): - r"""A request message for NetworkFirewallPolicies.AggregatedList. - See the method description for details. +class AggregatedListNetworkEdgeSecurityServicesRequest(proto.Message): + r"""A request message for + NetworkEdgeSecurityServices.AggregatedList. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -9196,7 +9058,7 @@ class AggregatedListNetworkFirewallPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -9257,9 +9119,9 @@ class AggregatedListNetworkFirewallPoliciesRequest(proto.Message): ) -class AggregatedListNodeGroupsRequest(proto.Message): - r"""A request message for NodeGroups.AggregatedList. See the - method description for details. +class AggregatedListNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for NetworkEndpointGroups.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -9443,9 +9305,9 @@ class AggregatedListNodeGroupsRequest(proto.Message): ) -class AggregatedListNodeTemplatesRequest(proto.Message): - r"""A request message for NodeTemplates.AggregatedList. See the - method description for details. +class AggregatedListNetworkFirewallPoliciesRequest(proto.Message): + r"""A request message for NetworkFirewallPolicies.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -9629,8 +9491,8 @@ class AggregatedListNodeTemplatesRequest(proto.Message): ) -class AggregatedListNodeTypesRequest(proto.Message): - r"""A request message for NodeTypes.AggregatedList. See the +class AggregatedListNodeGroupsRequest(proto.Message): + r"""A request message for NodeGroups.AggregatedList. See the method description for details. @@ -9815,9 +9677,9 @@ class AggregatedListNodeTypesRequest(proto.Message): ) -class AggregatedListPacketMirroringsRequest(proto.Message): - r"""A request message for PacketMirrorings.AggregatedList. See - the method description for details. +class AggregatedListNodeTemplatesRequest(proto.Message): + r"""A request message for NodeTemplates.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -10001,9 +9863,9 @@ class AggregatedListPacketMirroringsRequest(proto.Message): ) -class AggregatedListPublicDelegatedPrefixesRequest(proto.Message): - r"""A request message for PublicDelegatedPrefixes.AggregatedList. - See the method description for details. +class AggregatedListNodeTypesRequest(proto.Message): + r"""A request message for NodeTypes.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -10126,7 +9988,7 @@ class AggregatedListPublicDelegatedPrefixesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -10187,8 +10049,8 @@ class AggregatedListPublicDelegatedPrefixesRequest(proto.Message): ) -class AggregatedListRegionCommitmentsRequest(proto.Message): - r"""A request message for RegionCommitments.AggregatedList. See +class AggregatedListPacketMirroringsRequest(proto.Message): + r"""A request message for PacketMirrorings.AggregatedList. See the method description for details. @@ -10373,10 +10235,9 @@ class AggregatedListRegionCommitmentsRequest(proto.Message): ) -class AggregatedListRegionCompositeHealthChecksRequest(proto.Message): - r"""A request message for - RegionCompositeHealthChecks.AggregatedList. See the method - description for details. +class AggregatedListPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -10560,10 +10421,9 @@ class AggregatedListRegionCompositeHealthChecksRequest(proto.Message): ) -class AggregatedListRegionHealthAggregationPoliciesRequest(proto.Message): - r"""A request message for - RegionHealthAggregationPolicies.AggregatedList. See the method - description for details. +class AggregatedListRegionCommitmentsRequest(proto.Message): + r"""A request message for RegionCommitments.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -10686,7 +10546,7 @@ class AggregatedListRegionHealthAggregationPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -10747,9 +10607,9 @@ class AggregatedListRegionHealthAggregationPoliciesRequest(proto.Message): ) -class AggregatedListRegionHealthCheckServicesRequest(proto.Message): +class AggregatedListRegionCompositeHealthChecksRequest(proto.Message): r"""A request message for - RegionHealthCheckServices.AggregatedList. See the method + RegionCompositeHealthChecks.AggregatedList. See the method description for details. @@ -10934,9 +10794,10 @@ class AggregatedListRegionHealthCheckServicesRequest(proto.Message): ) -class AggregatedListRegionHealthSourcesRequest(proto.Message): - r"""A request message for RegionHealthSources.AggregatedList. See - the method description for details. +class AggregatedListRegionHealthAggregationPoliciesRequest(proto.Message): + r"""A request message for + RegionHealthAggregationPolicies.AggregatedList. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -11120,9 +10981,9 @@ class AggregatedListRegionHealthSourcesRequest(proto.Message): ) -class AggregatedListRegionNotificationEndpointsRequest(proto.Message): +class AggregatedListRegionHealthCheckServicesRequest(proto.Message): r"""A request message for - RegionNotificationEndpoints.AggregatedList. See the method + RegionHealthCheckServices.AggregatedList. See the method description for details. @@ -11307,194 +11168,8 @@ class AggregatedListRegionNotificationEndpointsRequest(proto.Message): ) -class AggregatedListReservationsRequest(proto.Message): - r"""A request message for Reservations.AggregatedList. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - filter (str): - A filter expression that filters resources listed in the - response. Most Compute resources support two types of filter - expressions: expressions that support regular expressions - and expressions that follow API improvement proposal - AIP-160. These two types of filter expressions cannot be - mixed in one request. - - If you want to use AIP-160, your expression must specify the - field name, an operator, and the value that you want to use - for filtering. The value must be a string, a number, or a - boolean. The operator must be either ``=``, ``!=``, ``>``, - ``<``, ``<=``, ``>=`` or ``:``. - - For example, if you are filtering Compute Engine instances, - you can exclude instances named ``example-instance`` by - specifying ``name != example-instance``. - - The ``:*`` comparison can be used to test whether a key has - been defined. For example, to find all objects with - ``owner`` label use: - - :: - - labels.owner:* - - You can also filter nested fields. For example, you could - specify ``scheduling.automaticRestart = false`` to include - instances only if they are not scheduled for automatic - restarts. You can use filtering on nested fields to filter - based onresource labels. - - To filter on multiple expressions, provide each separate - expression within parentheses. For example: - - :: - - (scheduling.automaticRestart = true) - (cpuPlatform = "Intel Skylake") - - By default, each expression is an ``AND`` expression. - However, you can include ``AND`` and ``OR`` expressions - explicitly. For example: - - :: - - (cpuPlatform = "Intel Skylake") OR - (cpuPlatform = "Intel Broadwell") AND - (scheduling.automaticRestart = true) - - If you want to use a regular expression, use the ``eq`` - (equal) or ``ne`` (not equal) operator against a single - un-parenthesized expression with or without quotes or - against multiple parenthesized expressions. Examples: - - ``fieldname eq unquoted literal`` - ``fieldname eq 'single quoted literal'`` - ``fieldname eq "double quoted literal"`` - ``(fieldname1 eq literal) (fieldname2 ne "literal")`` - - The literal value is interpreted as a regular expression - using GoogleRE2 library syntax. The literal value must match - the entire field. - - For example, to filter for instances that do not end with - name "instance", you would use ``name ne .*instance``. - - You cannot combine constraints on multiple fields using - regular expressions. - - This field is a member of `oneof`_ ``_filter``. - include_all_scopes (bool): - Indicates whether every visible scope for - each scope type (zone, region, global) should be - included in the response. For new resource types - added after this field, the flag has no effect - as new resource types will always include every - visible scope for each scope type in response. - For resource types which predate this field, if - this flag is omitted or false, only scopes of - the scope types where the resource type is - expected to be found will be included. - - This field is a member of `oneof`_ ``_include_all_scopes``. - max_results (int): - The maximum number of results per page that should be - returned. If the number of available results is larger than - ``maxResults``, Compute Engine returns a ``nextPageToken`` - that can be used to get the next page of results in - subsequent list requests. Acceptable values are ``0`` to - ``500``, inclusive. (Default: ``500``) - - This field is a member of `oneof`_ ``_max_results``. - order_by (str): - Sorts list results by a certain order. By default, results - are returned in alphanumerical order based on the resource - name. - - You can also sort results in descending order based on the - creation timestamp using - ``orderBy="creationTimestamp desc"``. This sorts results - based on the ``creationTimestamp`` field in reverse - chronological order (newest result first). Use this to sort - resources like operations so that the newest operation is - returned first. - - Currently, only sorting by ``name`` or - ``creationTimestamp desc`` is supported. - - This field is a member of `oneof`_ ``_order_by``. - page_token (str): - Specifies a page token to use. Set ``pageToken`` to the - ``nextPageToken`` returned by a previous list request to get - the next page of results. - - This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. - return_partial_success (bool): - Opt-in for partial success behavior which - provides partial results in case of failure. The - default value is false. - - For example, when partial success behavior is - enabled, aggregatedList for a single zone scope - either returns all resources in the zone or no - resources, with an error code. - - This field is a member of `oneof`_ ``_return_partial_success``. - service_project_number (int): - The Shared VPC service project id or service - project number for which aggregated list request - is invoked for subnetworks list-usable api. - - This field is a member of `oneof`_ ``_service_project_number``. - """ - - filter: str = proto.Field( - proto.STRING, - number=336120696, - optional=True, - ) - include_all_scopes: bool = proto.Field( - proto.BOOL, - number=391327988, - optional=True, - ) - max_results: int = proto.Field( - proto.UINT32, - number=54715419, - optional=True, - ) - order_by: str = proto.Field( - proto.STRING, - number=160562920, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=19994697, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, - optional=True, - ) - service_project_number: int = proto.Field( - proto.INT64, - number=316757497, - optional=True, - ) - - -class AggregatedListResourcePoliciesRequest(proto.Message): - r"""A request message for ResourcePolicies.AggregatedList. See +class AggregatedListRegionHealthSourcesRequest(proto.Message): + r"""A request message for RegionHealthSources.AggregatedList. See the method description for details. @@ -11618,7 +11293,7 @@ class AggregatedListResourcePoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -11679,8 +11354,9 @@ class AggregatedListResourcePoliciesRequest(proto.Message): ) -class AggregatedListRoutersRequest(proto.Message): - r"""A request message for Routers.AggregatedList. See the method +class AggregatedListRegionNotificationEndpointsRequest(proto.Message): + r"""A request message for + RegionNotificationEndpoints.AggregatedList. See the method description for details. @@ -11804,7 +11480,7 @@ class AggregatedListRoutersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -11865,9 +11541,9 @@ class AggregatedListRoutersRequest(proto.Message): ) -class AggregatedListSecurityPoliciesRequest(proto.Message): - r"""A request message for SecurityPolicies.AggregatedList. See - the method description for details. +class AggregatedListReservationsRequest(proto.Message): + r"""A request message for Reservations.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -11990,7 +11666,7 @@ class AggregatedListSecurityPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -12051,8 +11727,8 @@ class AggregatedListSecurityPoliciesRequest(proto.Message): ) -class AggregatedListServiceAttachmentsRequest(proto.Message): - r"""A request message for ServiceAttachments.AggregatedList. See +class AggregatedListResourcePoliciesRequest(proto.Message): + r"""A request message for ResourcePolicies.AggregatedList. See the method description for details. @@ -12176,7 +11852,7 @@ class AggregatedListServiceAttachmentsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -12237,9 +11913,9 @@ class AggregatedListServiceAttachmentsRequest(proto.Message): ) -class AggregatedListSslCertificatesRequest(proto.Message): - r"""A request message for SslCertificates.AggregatedList. See the - method description for details. +class AggregatedListRoutersRequest(proto.Message): + r"""A request message for Routers.AggregatedList. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -12362,7 +12038,7 @@ class AggregatedListSslCertificatesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -12423,9 +12099,9 @@ class AggregatedListSslCertificatesRequest(proto.Message): ) -class AggregatedListSslPoliciesRequest(proto.Message): - r"""A request message for SslPolicies.AggregatedList. See the - method description for details. +class AggregatedListSecurityPoliciesRequest(proto.Message): + r"""A request message for SecurityPolicies.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -12609,8 +12285,8 @@ class AggregatedListSslPoliciesRequest(proto.Message): ) -class AggregatedListStoragePoolTypesRequest(proto.Message): - r"""A request message for StoragePoolTypes.AggregatedList. See +class AggregatedListServiceAttachmentsRequest(proto.Message): + r"""A request message for ServiceAttachments.AggregatedList. See the method description for details. @@ -12734,7 +12410,7 @@ class AggregatedListStoragePoolTypesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -12795,8 +12471,8 @@ class AggregatedListStoragePoolTypesRequest(proto.Message): ) -class AggregatedListStoragePoolsRequest(proto.Message): - r"""A request message for StoragePools.AggregatedList. See the +class AggregatedListSslCertificatesRequest(proto.Message): + r"""A request message for SslCertificates.AggregatedList. See the method description for details. @@ -12920,7 +12596,7 @@ class AggregatedListStoragePoolsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -12981,8 +12657,8 @@ class AggregatedListStoragePoolsRequest(proto.Message): ) -class AggregatedListSubnetworksRequest(proto.Message): - r"""A request message for Subnetworks.AggregatedList. See the +class AggregatedListSslPoliciesRequest(proto.Message): + r"""A request message for SslPolicies.AggregatedList. See the method description for details. @@ -13106,7 +12782,7 @@ class AggregatedListSubnetworksRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -13124,42 +12800,193 @@ class AggregatedListSubnetworksRequest(proto.Message): is invoked for subnetworks list-usable api. This field is a member of `oneof`_ ``_service_project_number``. - views (str): - Defines the extra views returned back in the subnetwork - resource. Supported values: + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + include_all_scopes: bool = proto.Field( + proto.BOOL, + number=391327988, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + service_project_number: int = proto.Field( + proto.INT64, + number=316757497, + optional=True, + ) + + +class AggregatedListStoragePoolTypesRequest(proto.Message): + r"""A request message for StoragePoolTypes.AggregatedList. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: :: - - WITH_UTILIZATION: Utilization data is included in the - response. + labels.owner:* - Check the Views enum for the list of possible values. + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. - This field is a member of `oneof`_ ``_views``. - """ + To filter on multiple expressions, provide each separate + expression within parentheses. For example: - class Views(proto.Enum): - r"""Defines the extra views returned back in the subnetwork resource. - Supported values: + :: - :: + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") - - WITH_UTILIZATION: Utilization data is included in the - response. + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: - Values: - UNDEFINED_VIEWS (0): - A value indicating that the enum field is not - set. - DEFAULT (115302945): - No description available. - WITH_UTILIZATION (504090633): - Utilization data is included in the response. - """ + :: - UNDEFINED_VIEWS = 0 - DEFAULT = 115302945 - WITH_UTILIZATION = 504090633 + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + include_all_scopes (bool): + Indicates whether every visible scope for + each scope type (zone, region, global) should be + included in the response. For new resource types + added after this field, the flag has no effect + as new resource types will always include every + visible scope for each scope type in response. + For resource types which predate this field, if + this flag is omitted or false, only scopes of + the scope types where the resource type is + expected to be found will be included. + + This field is a member of `oneof`_ ``_include_all_scopes``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + service_project_number (int): + The Shared VPC service project id or service + project number for which aggregated list request + is invoked for subnetworks list-usable api. + + This field is a member of `oneof`_ ``_service_project_number``. + """ filter: str = proto.Field( proto.STRING, @@ -13200,16 +13027,11 @@ class Views(proto.Enum): number=316757497, optional=True, ) - views: str = proto.Field( - proto.STRING, - number=112204398, - optional=True, - ) -class AggregatedListTargetHttpProxiesRequest(proto.Message): - r"""A request message for TargetHttpProxies.AggregatedList. See - the method description for details. +class AggregatedListStoragePoolsRequest(proto.Message): + r"""A request message for StoragePools.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -13332,7 +13154,7 @@ class AggregatedListTargetHttpProxiesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -13393,9 +13215,9 @@ class AggregatedListTargetHttpProxiesRequest(proto.Message): ) -class AggregatedListTargetHttpsProxiesRequest(proto.Message): - r"""A request message for TargetHttpsProxies.AggregatedList. See - the method description for details. +class AggregatedListSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -13518,7 +13340,7 @@ class AggregatedListTargetHttpsProxiesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -13536,193 +13358,42 @@ class AggregatedListTargetHttpsProxiesRequest(proto.Message): is invoked for subnetworks list-usable api. This field is a member of `oneof`_ ``_service_project_number``. - """ - - filter: str = proto.Field( - proto.STRING, - number=336120696, - optional=True, - ) - include_all_scopes: bool = proto.Field( - proto.BOOL, - number=391327988, - optional=True, - ) - max_results: int = proto.Field( - proto.UINT32, - number=54715419, - optional=True, - ) - order_by: str = proto.Field( - proto.STRING, - number=160562920, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=19994697, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, - optional=True, - ) - service_project_number: int = proto.Field( - proto.INT64, - number=316757497, - optional=True, - ) - - -class AggregatedListTargetInstancesRequest(proto.Message): - r"""A request message for TargetInstances.AggregatedList. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - filter (str): - A filter expression that filters resources listed in the - response. Most Compute resources support two types of filter - expressions: expressions that support regular expressions - and expressions that follow API improvement proposal - AIP-160. These two types of filter expressions cannot be - mixed in one request. - - If you want to use AIP-160, your expression must specify the - field name, an operator, and the value that you want to use - for filtering. The value must be a string, a number, or a - boolean. The operator must be either ``=``, ``!=``, ``>``, - ``<``, ``<=``, ``>=`` or ``:``. - - For example, if you are filtering Compute Engine instances, - you can exclude instances named ``example-instance`` by - specifying ``name != example-instance``. - - The ``:*`` comparison can be used to test whether a key has - been defined. For example, to find all objects with - ``owner`` label use: - - :: - - labels.owner:* - - You can also filter nested fields. For example, you could - specify ``scheduling.automaticRestart = false`` to include - instances only if they are not scheduled for automatic - restarts. You can use filtering on nested fields to filter - based onresource labels. - - To filter on multiple expressions, provide each separate - expression within parentheses. For example: - - :: - - (scheduling.automaticRestart = true) - (cpuPlatform = "Intel Skylake") - - By default, each expression is an ``AND`` expression. - However, you can include ``AND`` and ``OR`` expressions - explicitly. For example: + views (str): + Defines the extra views returned back in the subnetwork + resource. Supported values: :: - (cpuPlatform = "Intel Skylake") OR - (cpuPlatform = "Intel Broadwell") AND - (scheduling.automaticRestart = true) - - If you want to use a regular expression, use the ``eq`` - (equal) or ``ne`` (not equal) operator against a single - un-parenthesized expression with or without quotes or - against multiple parenthesized expressions. Examples: - - ``fieldname eq unquoted literal`` - ``fieldname eq 'single quoted literal'`` - ``fieldname eq "double quoted literal"`` - ``(fieldname1 eq literal) (fieldname2 ne "literal")`` - - The literal value is interpreted as a regular expression - using GoogleRE2 library syntax. The literal value must match - the entire field. - - For example, to filter for instances that do not end with - name "instance", you would use ``name ne .*instance``. - - You cannot combine constraints on multiple fields using - regular expressions. - - This field is a member of `oneof`_ ``_filter``. - include_all_scopes (bool): - Indicates whether every visible scope for - each scope type (zone, region, global) should be - included in the response. For new resource types - added after this field, the flag has no effect - as new resource types will always include every - visible scope for each scope type in response. - For resource types which predate this field, if - this flag is omitted or false, only scopes of - the scope types where the resource type is - expected to be found will be included. - - This field is a member of `oneof`_ ``_include_all_scopes``. - max_results (int): - The maximum number of results per page that should be - returned. If the number of available results is larger than - ``maxResults``, Compute Engine returns a ``nextPageToken`` - that can be used to get the next page of results in - subsequent list requests. Acceptable values are ``0`` to - ``500``, inclusive. (Default: ``500``) - - This field is a member of `oneof`_ ``_max_results``. - order_by (str): - Sorts list results by a certain order. By default, results - are returned in alphanumerical order based on the resource - name. + - WITH_UTILIZATION: Utilization data is included in the + response. - You can also sort results in descending order based on the - creation timestamp using - ``orderBy="creationTimestamp desc"``. This sorts results - based on the ``creationTimestamp`` field in reverse - chronological order (newest result first). Use this to sort - resources like operations so that the newest operation is - returned first. + Check the Views enum for the list of possible values. - Currently, only sorting by ``name`` or - ``creationTimestamp desc`` is supported. + This field is a member of `oneof`_ ``_views``. + """ - This field is a member of `oneof`_ ``_order_by``. - page_token (str): - Specifies a page token to use. Set ``pageToken`` to the - ``nextPageToken`` returned by a previous list request to get - the next page of results. + class Views(proto.Enum): + r"""Defines the extra views returned back in the subnetwork resource. + Supported values: - This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. - return_partial_success (bool): - Opt-in for partial success behavior which - provides partial results in case of failure. The - default value is false. + :: - For example, when partial success behavior is - enabled, aggregatedList for a single zone scope - either returns all resources in the zone or no - resources, with an error code. + - WITH_UTILIZATION: Utilization data is included in the + response. - This field is a member of `oneof`_ ``_return_partial_success``. - service_project_number (int): - The Shared VPC service project id or service - project number for which aggregated list request - is invoked for subnetworks list-usable api. + Values: + UNDEFINED_VIEWS (0): + A value indicating that the enum field is not + set. + DEFAULT (115302945): + No description available. + WITH_UTILIZATION (504090633): + Utilization data is included in the response. + """ - This field is a member of `oneof`_ ``_service_project_number``. - """ + UNDEFINED_VIEWS = 0 + DEFAULT = 115302945 + WITH_UTILIZATION = 504090633 filter: str = proto.Field( proto.STRING, @@ -13763,11 +13434,16 @@ class AggregatedListTargetInstancesRequest(proto.Message): number=316757497, optional=True, ) + views: str = proto.Field( + proto.STRING, + number=112204398, + optional=True, + ) -class AggregatedListTargetPoolsRequest(proto.Message): - r"""A request message for TargetPools.AggregatedList. See the - method description for details. +class AggregatedListTargetHttpProxiesRequest(proto.Message): + r"""A request message for TargetHttpProxies.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -13890,7 +13566,7 @@ class AggregatedListTargetPoolsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -13951,8 +13627,8 @@ class AggregatedListTargetPoolsRequest(proto.Message): ) -class AggregatedListTargetTcpProxiesRequest(proto.Message): - r"""A request message for TargetTcpProxies.AggregatedList. See +class AggregatedListTargetHttpsProxiesRequest(proto.Message): + r"""A request message for TargetHttpsProxies.AggregatedList. See the method description for details. @@ -14137,9 +13813,9 @@ class AggregatedListTargetTcpProxiesRequest(proto.Message): ) -class AggregatedListTargetVpnGatewaysRequest(proto.Message): - r"""A request message for TargetVpnGateways.AggregatedList. See - the method description for details. +class AggregatedListTargetInstancesRequest(proto.Message): + r"""A request message for TargetInstances.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -14323,9 +13999,9 @@ class AggregatedListTargetVpnGatewaysRequest(proto.Message): ) -class AggregatedListUrlMapsRequest(proto.Message): - r"""A request message for UrlMaps.AggregatedList. See the method - description for details. +class AggregatedListTargetPoolsRequest(proto.Message): + r"""A request message for TargetPools.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -14448,7 +14124,7 @@ class AggregatedListUrlMapsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -14509,9 +14185,9 @@ class AggregatedListUrlMapsRequest(proto.Message): ) -class AggregatedListVpnGatewaysRequest(proto.Message): - r"""A request message for VpnGateways.AggregatedList. See the - method description for details. +class AggregatedListTargetTcpProxiesRequest(proto.Message): + r"""A request message for TargetTcpProxies.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -14634,7 +14310,7 @@ class AggregatedListVpnGatewaysRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -14695,9 +14371,567 @@ class AggregatedListVpnGatewaysRequest(proto.Message): ) -class AggregatedListVpnTunnelsRequest(proto.Message): - r"""A request message for VpnTunnels.AggregatedList. See the - method description for details. +class AggregatedListTargetVpnGatewaysRequest(proto.Message): + r"""A request message for TargetVpnGateways.AggregatedList. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: + + :: + + labels.owner:* + + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. + + To filter on multiple expressions, provide each separate + expression within parentheses. For example: + + :: + + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") + + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + + :: + + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + include_all_scopes (bool): + Indicates whether every visible scope for + each scope type (zone, region, global) should be + included in the response. For new resource types + added after this field, the flag has no effect + as new resource types will always include every + visible scope for each scope type in response. + For resource types which predate this field, if + this flag is omitted or false, only scopes of + the scope types where the resource type is + expected to be found will be included. + + This field is a member of `oneof`_ ``_include_all_scopes``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + service_project_number (int): + The Shared VPC service project id or service + project number for which aggregated list request + is invoked for subnetworks list-usable api. + + This field is a member of `oneof`_ ``_service_project_number``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + include_all_scopes: bool = proto.Field( + proto.BOOL, + number=391327988, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + service_project_number: int = proto.Field( + proto.INT64, + number=316757497, + optional=True, + ) + + +class AggregatedListUrlMapsRequest(proto.Message): + r"""A request message for UrlMaps.AggregatedList. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: + + :: + + labels.owner:* + + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. + + To filter on multiple expressions, provide each separate + expression within parentheses. For example: + + :: + + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") + + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + + :: + + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + include_all_scopes (bool): + Indicates whether every visible scope for + each scope type (zone, region, global) should be + included in the response. For new resource types + added after this field, the flag has no effect + as new resource types will always include every + visible scope for each scope type in response. + For resource types which predate this field, if + this flag is omitted or false, only scopes of + the scope types where the resource type is + expected to be found will be included. + + This field is a member of `oneof`_ ``_include_all_scopes``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Name of the project scoping this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + service_project_number (int): + The Shared VPC service project id or service + project number for which aggregated list request + is invoked for subnetworks list-usable api. + + This field is a member of `oneof`_ ``_service_project_number``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + include_all_scopes: bool = proto.Field( + proto.BOOL, + number=391327988, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + service_project_number: int = proto.Field( + proto.INT64, + number=316757497, + optional=True, + ) + + +class AggregatedListVpnGatewaysRequest(proto.Message): + r"""A request message for VpnGateways.AggregatedList. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: + + :: + + labels.owner:* + + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. + + To filter on multiple expressions, provide each separate + expression within parentheses. For example: + + :: + + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") + + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + + :: + + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + include_all_scopes (bool): + Indicates whether every visible scope for + each scope type (zone, region, global) should be + included in the response. For new resource types + added after this field, the flag has no effect + as new resource types will always include every + visible scope for each scope type in response. + For resource types which predate this field, if + this flag is omitted or false, only scopes of + the scope types where the resource type is + expected to be found will be included. + + This field is a member of `oneof`_ ``_include_all_scopes``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + service_project_number (int): + The Shared VPC service project id or service + project number for which aggregated list request + is invoked for subnetworks list-usable api. + + This field is a member of `oneof`_ ``_service_project_number``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + include_all_scopes: bool = proto.Field( + proto.BOOL, + number=391327988, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + service_project_number: int = proto.Field( + proto.INT64, + number=316757497, + optional=True, + ) + + +class AggregatedListVpnTunnelsRequest(proto.Message): + r"""A request message for VpnTunnels.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -16457,7 +16691,7 @@ class AttachedDiskInitializeParams(proto.Message): Tag keys and values have the same definition as resource manager tags. Keys and values can be either in numeric format, such as ``tagKeys/{tag_key_id}`` and - ``tagValues/456`` or in namespaced format such as + ``tagValues/{tag_value_id}`` or in namespaced format such as ``{org_id|project_id}/{tag_key_short_name}`` and ``{tag_value_short_name}``. The field is ignored (both PUT & PATCH) when empty. @@ -17627,6 +17861,18 @@ class AutoscalingPolicy(proto.Message): During overlapping periods the greatest min_required_replicas of all scaling schedules is applied. Up to 128 scaling schedules are allowed. + stabilization_period_sec (int): + The number of seconds that autoscaler waits for load + stabilization before making scale-in decisions. This is + referred to as the `stabilization + period `__. + This might appear as a delay in scaling in but it is an + important mechanism for your application to not have + fluctuating size due to short term load fluctuations. + + The default stabilization period is 600 seconds. + + This field is a member of `oneof`_ ``_stabilization_period_sec``. """ class Mode(proto.Enum): @@ -17724,6 +17970,11 @@ class Mode(proto.Enum): message="AutoscalingPolicyScalingSchedule", ) ) + stabilization_period_sec: int = proto.Field( + proto.INT32, + number=420200243, + optional=True, + ) class AutoscalingPolicyCpuUtilization(proto.Message): @@ -24999,6 +25250,130 @@ class CancelRegionInstanceGroupManagerResizeRequestRequest(proto.Message): ) +class CancelRequestRemovePeeringNetworkRequest(proto.Message): + r"""A request message for Networks.CancelRequestRemovePeering. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network (str): + Name of the network resource to remove + peering from. + networks_cancel_request_remove_peering_request_resource (google.cloud.compute_v1.types.NetworksCancelRequestRemovePeeringRequest): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + network: str = proto.Field( + proto.STRING, + number=232872494, + ) + networks_cancel_request_remove_peering_request_resource: "NetworksCancelRequestRemovePeeringRequest" = proto.Field( + proto.MESSAGE, + number=177326909, + message="NetworksCancelRequestRemovePeeringRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + +class CancelRolloutRequest(proto.Message): + r"""A request message for Rollouts.Cancel. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollback (bool): + Optional. If true, then the ongoing rollout + must be rolled back. Else, just cancel the + rollout without taking any further actions. Note + that products must support at least one of these + options, however, it does not need to support + both. + + This field is a member of `oneof`_ ``_rollback``. + rollout (str): + Name of the Rollout resource to cancel. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollback: bool = proto.Field( + proto.BOOL, + number=277151460, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class CircuitBreakers(proto.Message): r"""Settings controlling the volume of requests, connections and retries to this backend service. @@ -25457,7 +25832,7 @@ class Commitment(proto.Message): GENERAL_PURPOSE_E2,GENERAL_PURPOSE_N2, GENERAL_PURPOSE_N2D,GENERAL_PURPOSE_N4, GENERAL_PURPOSE_T2D,GRAPHICS_OPTIMIZED, - GRAPHICS_OPTIMIZED_G4,MEMORY_OPTIMIZED, + GRAPHICS_OPTIMIZED_G4,GRAPHICS_OPTIMIZED_G4_VGPU,MEMORY_OPTIMIZED, MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, STORAGE_OPTIMIZED_Z3. For example, type MEMORY_OPTIMIZED specifies a commitment that applies only to eligible @@ -25567,7 +25942,7 @@ class Type(proto.Enum): GENERAL_PURPOSE_E2,GENERAL_PURPOSE_N2, GENERAL_PURPOSE_N2D,GENERAL_PURPOSE_N4, GENERAL_PURPOSE_T2D,GRAPHICS_OPTIMIZED, - GRAPHICS_OPTIMIZED_G4,MEMORY_OPTIMIZED, + GRAPHICS_OPTIMIZED_G4,GRAPHICS_OPTIMIZED_G4_VGPU,MEMORY_OPTIMIZED, MEMORY_OPTIMIZED_M3,MEMORY_OPTIMIZED_X4, STORAGE_OPTIMIZED_Z3. For example, type MEMORY_OPTIMIZED specifies a commitment that applies only to eligible resources of memory optimized M1 and M2 machine @@ -25626,6 +26001,8 @@ class Type(proto.Enum): No description available. GRAPHICS_OPTIMIZED_G4 (54029369): No description available. + GRAPHICS_OPTIMIZED_G4_VGPU (298988732): + No description available. MEMORY_OPTIMIZED (281753417): No description available. MEMORY_OPTIMIZED_M3 (276301372): @@ -25692,6 +26069,7 @@ class Type(proto.Enum): GENERAL_PURPOSE_T2D = 232477166 GRAPHICS_OPTIMIZED = 68500563 GRAPHICS_OPTIMIZED_G4 = 54029369 + GRAPHICS_OPTIMIZED_G4_VGPU = 298988732 MEMORY_OPTIMIZED = 281753417 MEMORY_OPTIMIZED_M3 = 276301372 MEMORY_OPTIMIZED_M4 = 276301373 @@ -28604,6 +28982,65 @@ class DeleteGlobalPublicDelegatedPrefixeRequest(proto.Message): ) +class DeleteGlobalVmExtensionPolicyRequest(proto.Message): + r"""A request message for GlobalVmExtensionPolicies.Delete. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + global_vm_extension_policy (str): + Name of the global VM extension policy to + purge scoped resources for. + global_vm_extension_policy_rollout_operation_rollout_input_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutInput): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + global_vm_extension_policy: str = proto.Field( + proto.STRING, + number=8334110, + ) + global_vm_extension_policy_rollout_operation_rollout_input_resource: "GlobalVmExtensionPolicyRolloutOperationRolloutInput" = proto.Field( + proto.MESSAGE, + number=147209176, + message="GlobalVmExtensionPolicyRolloutOperationRolloutInput", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + class DeleteHealthCheckRequest(proto.Message): r"""A request message for HealthChecks.Delete. See the method description for details. @@ -31952,23 +32389,16 @@ class DeleteResourcePolicyRequest(proto.Message): ) -class DeleteRoutePolicyRouterRequest(proto.Message): - r"""A request message for Routers.DeleteRoutePolicy. See the - method description for details. +class DeleteRolloutPlanRequest(proto.Message): + r"""A request message for RolloutPlans.Delete. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - policy (str): - The Policy name for this request. Name must - conform to RFC1035 - - This field is a member of `oneof`_ ``_policy``. project (str): Project ID for this request. - region (str): - Name of the region for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -31991,45 +32421,93 @@ class DeleteRoutePolicyRouterRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - router (str): - Name of the Router resource where Route - Policy is defined. + rollout_plan (str): + Name of the RolloutPlan resource to delete. """ - policy: str = proto.Field( + project: str = proto.Field( proto.STRING, - number=91071794, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, optional=True, ) - project: str = proto.Field( + rollout_plan: str = proto.Field( proto.STRING, - number=227560217, + number=459057399, ) - region: str = proto.Field( + + +class DeleteRolloutRequest(proto.Message): + r"""A request message for Rollouts.Delete. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Name of the Rollout resource to delete. + """ + + project: str = proto.Field( proto.STRING, - number=138946292, + number=227560217, ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - router: str = proto.Field( + rollout: str = proto.Field( proto.STRING, - number=148608841, + number=303366577, ) -class DeleteRouteRequest(proto.Message): - r"""A request message for Routes.Delete. See the method - description for details. +class DeleteRoutePolicyRouterRequest(proto.Message): + r"""A request message for Routers.DeleteRoutePolicy. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + policy (str): + The Policy name for this request. Name must + conform to RFC1035 + + This field is a member of `oneof`_ ``_policy``. project (str): Project ID for this request. + region (str): + Name of the region for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -32052,27 +32530,37 @@ class DeleteRouteRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - route (str): - Name of the Route resource to delete. + router (str): + Name of the Router resource where Route + Policy is defined. """ + policy: str = proto.Field( + proto.STRING, + number=91071794, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - route: str = proto.Field( + router: str = proto.Field( proto.STRING, - number=108704329, + number=148608841, ) -class DeleteRouterRequest(proto.Message): - r"""A request message for Routers.Delete. See the method +class DeleteRouteRequest(proto.Message): + r"""A request message for Routes.Delete. See the method description for details. @@ -32081,8 +32569,59 @@ class DeleteRouterRequest(proto.Message): Attributes: project (str): Project ID for this request. - region (str): - Name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + route (str): + Name of the Route resource to delete. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + route: str = proto.Field( + proto.STRING, + number=108704329, + ) + + +class DeleteRouterRequest(proto.Message): + r"""A request message for Routers.Delete. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + region (str): + Name of the region for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -35186,7 +35725,7 @@ class DiskParams(proto.Message): Tag keys and values have the same definition as resource manager tags. Keys and values can be either in numeric format, such as ``tagKeys/{tag_key_id}`` and - ``tagValues/456`` or in namespaced format such as + ``tagValues/{tag_value_id}`` or in namespaced format such as ``{org_id|project_id}/{tag_key_short_name}`` and ``{tag_value_short_name}``. The field is ignored (both PUT & PATCH) when empty. @@ -37589,8 +38128,8 @@ class FirewallPolicy(proto.Message): This field is a member of `oneof`_ ``_parent``. policy_type (str): - The type of the firewall policy. This field can be - eitherVPC_POLICY or RDMA_ROCE_POLICY. + The type of the firewall policy. This field can be one of + VPC_POLICY, RDMA_ROCE_POLICY or ULL_POLICY. Note: if not specified then VPC_POLICY will be used. Check the PolicyType enum for the list of possible values. @@ -37642,8 +38181,8 @@ class FirewallPolicy(proto.Message): """ class PolicyType(proto.Enum): - r"""The type of the firewall policy. This field can be eitherVPC_POLICY - or RDMA_ROCE_POLICY. + r"""The type of the firewall policy. This field can be one of + VPC_POLICY, RDMA_ROCE_POLICY or ULL_POLICY. Note: if not specified then VPC_POLICY will be used. @@ -37653,12 +38192,15 @@ class PolicyType(proto.Enum): set. RDMA_ROCE_POLICY (148757145): No description available. + ULL_POLICY (100494364): + No description available. VPC_POLICY (74319208): No description available. """ UNDEFINED_POLICY_TYPE = 0 RDMA_ROCE_POLICY = 148757145 + ULL_POLICY = 100494364 VPC_POLICY = 74319208 associations: MutableSequence["FirewallPolicyAssociation"] = proto.RepeatedField( @@ -38473,8 +39015,8 @@ class FixedOrPercent(proto.Message): Attributes: calculated (int): - Output only. [Output Only] Absolute value of VM instances - calculated based on the specific mode. + Output only. Absolute value of VM instances calculated based + on the specific mode. :: @@ -42513,6 +43055,28 @@ class GetGlobalPublicDelegatedPrefixeRequest(proto.Message): ) +class GetGlobalVmExtensionPolicyRequest(proto.Message): + r"""A request message for GlobalVmExtensionPolicies.Get. See the + method description for details. + + Attributes: + global_vm_extension_policy (str): + Name of the GlobalVmExtensionPolicy resource + to return. + project (str): + Project ID for this request. + """ + + global_vm_extension_policy: str = proto.Field( + proto.STRING, + number=8334110, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + + class GetGuestAttributesInstanceRequest(proto.Message): r"""A request message for Instances.GetGuestAttributes. See the method description for details. @@ -43121,41 +43685,8 @@ class GetIamPolicyInterconnectGroupRequest(proto.Message): ) -class GetIamPolicyLicenseRequest(proto.Message): - r"""A request message for Licenses.GetIamPolicy. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class GetIamPolicyMachineImageRequest(proto.Message): - r"""A request message for MachineImages.GetIamPolicy. See the +class GetIamPolicyLicenseCodeRequest(proto.Message): + r"""A request message for LicenseCodes.GetIamPolicy. See the method description for details. @@ -43187,80 +43718,8 @@ class GetIamPolicyMachineImageRequest(proto.Message): ) -class GetIamPolicyNetworkAttachmentRequest(proto.Message): - r"""A request message for NetworkAttachments.GetIamPolicy. See - the method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - region (str): - The name of the region for this request. - resource (str): - Name or id of the resource for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class GetIamPolicyNetworkFirewallPolicyRequest(proto.Message): - r"""A request message for NetworkFirewallPolicies.GetIamPolicy. - See the method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class GetIamPolicyNodeGroupRequest(proto.Message): - r"""A request message for NodeGroups.GetIamPolicy. See the method +class GetIamPolicyLicenseRequest(proto.Message): + r"""A request message for Licenses.GetIamPolicy. See the method description for details. @@ -43275,8 +43734,6 @@ class GetIamPolicyNodeGroupRequest(proto.Message): Project ID for this request. resource (str): Name or id of the resource for this request. - zone (str): - The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -43292,14 +43749,10 @@ class GetIamPolicyNodeGroupRequest(proto.Message): proto.STRING, number=195806222, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class GetIamPolicyNodeTemplateRequest(proto.Message): - r"""A request message for NodeTemplates.GetIamPolicy. See the +class GetIamPolicyMachineImageRequest(proto.Message): + r"""A request message for MachineImages.GetIamPolicy. See the method description for details. @@ -43312,8 +43765,6 @@ class GetIamPolicyNodeTemplateRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. """ @@ -43327,18 +43778,14 @@ class GetIamPolicyNodeTemplateRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) -class GetIamPolicyRegionBackendBucketRequest(proto.Message): - r"""A request message for RegionBackendBuckets.GetIamPolicy. See +class GetIamPolicyNetworkAttachmentRequest(proto.Message): + r"""A request message for NetworkAttachments.GetIamPolicy. See the method description for details. @@ -43376,9 +43823,9 @@ class GetIamPolicyRegionBackendBucketRequest(proto.Message): ) -class GetIamPolicyRegionBackendServiceRequest(proto.Message): - r"""A request message for RegionBackendServices.GetIamPolicy. See - the method description for details. +class GetIamPolicyNetworkFirewallPolicyRequest(proto.Message): + r"""A request message for NetworkFirewallPolicies.GetIamPolicy. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -43390,8 +43837,6 @@ class GetIamPolicyRegionBackendServiceRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. """ @@ -43405,19 +43850,15 @@ class GetIamPolicyRegionBackendServiceRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) -class GetIamPolicyRegionDiskRequest(proto.Message): - r"""A request message for RegionDisks.GetIamPolicy. See the - method description for details. +class GetIamPolicyNodeGroupRequest(proto.Message): + r"""A request message for NodeGroups.GetIamPolicy. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -43429,10 +43870,10 @@ class GetIamPolicyRegionDiskRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. + zone (str): + The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -43444,59 +43885,215 @@ class GetIamPolicyRegionDiskRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) - - -class GetIamPolicyRegionInstantSnapshotGroupRequest(proto.Message): - r"""A request message for - RegionInstantSnapshotGroups.GetIamPolicy. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - region (str): - The name of the region for this request. - resource (str): - Name or id of the resource for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - resource: str = proto.Field( + zone: str = proto.Field( proto.STRING, - number=195806222, + number=3744684, ) -class GetIamPolicyRegionInstantSnapshotRequest(proto.Message): - r"""A request message for RegionInstantSnapshots.GetIamPolicy. - See the method description for details. +class GetIamPolicyNodeTemplateRequest(proto.Message): + r"""A request message for NodeTemplates.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyRegionBackendBucketRequest(proto.Message): + r"""A request message for RegionBackendBuckets.GetIamPolicy. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyRegionBackendServiceRequest(proto.Message): + r"""A request message for RegionBackendServices.GetIamPolicy. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyRegionDiskRequest(proto.Message): + r"""A request message for RegionDisks.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyRegionInstantSnapshotGroupRequest(proto.Message): + r"""A request message for + RegionInstantSnapshotGroups.GetIamPolicy. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyRegionInstantSnapshotRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.GetIamPolicy. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -46213,6 +46810,49 @@ class GetResourcePolicyRequest(proto.Message): ) +class GetRolloutPlanRequest(proto.Message): + r"""A request message for RolloutPlans.Get. See the method + description for details. + + Attributes: + project (str): + Project ID for this request. + rollout_plan (str): + Name of the persistent rollout plan to + return. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + rollout_plan: str = proto.Field( + proto.STRING, + number=459057399, + ) + + +class GetRolloutRequest(proto.Message): + r"""A request message for Rollouts.Get. See the method + description for details. + + Attributes: + project (str): + Project ID for this request. + rollout (str): + Name of the persistent rollout to return. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class GetRoutePolicyRouterRequest(proto.Message): r"""A request message for Routers.GetRoutePolicy. See the method description for details. @@ -47194,13 +47834,12 @@ class GetVersionOperationMetadataSbomInfo(proto.Message): Attributes: current_component_versions (MutableMapping[str, str]): - SBOM versions currently applied to the - resource. The key is the component name and the - value is the version. + A mapping of components to their + currently-applied versions or other appropriate + identifiers. target_component_versions (MutableMapping[str, str]): - SBOM versions scheduled for the next - maintenance. The key is the component name and - the value is the version. + A mapping of components to their target + versions or other appropriate identifiers. """ current_component_versions: MutableMapping[str, str] = proto.MapField( @@ -47893,6 +48532,649 @@ class GlobalSetPolicyRequest(proto.Message): ) +class GlobalVmExtensionPolicy(proto.Message): + r"""Message describing GlobalVmExtensionPolicy object. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + creation_timestamp (str): + Output only. [Output Only] Creation timestamp inRFC3339 text + format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + + This field is a member of `oneof`_ ``_description``. + extension_policies (MutableMapping[str, google.cloud.compute_v1.types.GlobalVmExtensionPolicyExtensionPolicy]): + Required. Map from extension (eg: "cloudops") + to its policy configuration. The key is the name + of the extension. + id (int): + Output only. [Output Only] The unique identifier for the + resource. This identifier is defined by the server. + + This field is a member of `oneof`_ ``_id``. + instance_selectors (MutableSequence[google.cloud.compute_v1.types.GlobalVmExtensionPolicyInstanceSelector]): + Optional. Selector to target VMs for a policy. There is a + logical "AND" between instance_selectors. + kind (str): + Output only. [Output Only] Type of the resource. + Alwayscompute#globalVmExtensionPolicy for + globalVmExtensionPolicies. + + This field is a member of `oneof`_ ``_kind``. + name (str): + Name of the resource. Provided by the client when the + resource is created. The name must be 1-63 characters long, + and comply withRFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + + This field is a member of `oneof`_ ``_name``. + priority (int): + Optional. Used to resolve conflicts when + multiple policies are active for the same + extension. Defaults to 0. + + Larger the number, higher the priority. When the + priority is the same, the policy with the newer + create time has higher priority. + + This field is a member of `oneof`_ ``_priority``. + rollout_operation (google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperation): + Required. The rollout strategy and status. + + This field is a member of `oneof`_ ``_rollout_operation``. + scoped_resource_status (str): + Output only. [Output Only] The scoped resource status. It's + only for tracking the purging status of the policy. Check + the ScopedResourceStatus enum for the list of possible + values. + + This field is a member of `oneof`_ ``_scoped_resource_status``. + self_link (str): + Output only. [Output Only] Server-defined fully-qualified + URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + Output only. [Output Only] Server-defined URL for this + resource's resource id. + + This field is a member of `oneof`_ ``_self_link_with_id``. + update_timestamp (str): + Output only. [Output Only] Update timestamp inRFC3339 text + format. + + This field is a member of `oneof`_ ``_update_timestamp``. + """ + + class ScopedResourceStatus(proto.Enum): + r"""Output only. [Output Only] The scoped resource status. It's only for + tracking the purging status of the policy. + + Values: + UNDEFINED_SCOPED_RESOURCE_STATUS (0): + A value indicating that the enum field is not + set. + SCOPED_RESOURCE_STATUS_DELETING (404198387): + The zonal policies are being deleted. + SCOPED_RESOURCE_STATUS_UNSPECIFIED (437941996): + Default value. This value is unused. + """ + + UNDEFINED_SCOPED_RESOURCE_STATUS = 0 + SCOPED_RESOURCE_STATUS_DELETING = 404198387 + SCOPED_RESOURCE_STATUS_UNSPECIFIED = 437941996 + + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + extension_policies: MutableMapping[ + str, "GlobalVmExtensionPolicyExtensionPolicy" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=227761488, + message="GlobalVmExtensionPolicyExtensionPolicy", + ) + id: int = proto.Field( + proto.UINT64, + number=3355, + optional=True, + ) + instance_selectors: MutableSequence["GlobalVmExtensionPolicyInstanceSelector"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=520298826, + message="GlobalVmExtensionPolicyInstanceSelector", + ) + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + priority: int = proto.Field( + proto.INT32, + number=445151652, + optional=True, + ) + rollout_operation: "GlobalVmExtensionPolicyRolloutOperation" = proto.Field( + proto.MESSAGE, + number=486746201, + optional=True, + message="GlobalVmExtensionPolicyRolloutOperation", + ) + scoped_resource_status: str = proto.Field( + proto.STRING, + number=181976980, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + self_link_with_id: str = proto.Field( + proto.STRING, + number=44520962, + optional=True, + ) + update_timestamp: str = proto.Field( + proto.STRING, + number=120894752, + optional=True, + ) + + +class GlobalVmExtensionPolicyExtensionPolicy(proto.Message): + r"""Policy for a single extension. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pinned_version (str): + Optional. The version pinning for the + extension. If empty, the extension will be + installed with the latest version released by + the extension producer. + + This field is a member of `oneof`_ ``_pinned_version``. + string_config (str): + Optional. String configuration. Any string + payload that the extension understands. + + This field is a member of `oneof`_ ``_string_config``. + """ + + pinned_version: str = proto.Field( + proto.STRING, + number=446267249, + optional=True, + ) + string_config: str = proto.Field( + proto.STRING, + number=318905136, + optional=True, + ) + + +class GlobalVmExtensionPolicyInstanceSelector(proto.Message): + r"""Selector to target VMs for a zone VM extension policy. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + label_selector (google.cloud.compute_v1.types.GlobalVmExtensionPolicyLabelSelector): + Optional. Labels within the LabelSelector are + OR'd. + + This field is a member of `oneof`_ ``_label_selector``. + """ + + label_selector: "GlobalVmExtensionPolicyLabelSelector" = proto.Field( + proto.MESSAGE, + number=349780170, + optional=True, + message="GlobalVmExtensionPolicyLabelSelector", + ) + + +class GlobalVmExtensionPolicyLabelSelector(proto.Message): + r"""A LabelSelector is applicable for a VM only if it matches all + labels in the LabelSelector. + + Attributes: + inclusion_labels (MutableMapping[str, str]): + Optional. Labels as key value pairs. + A VM should contain all the pairs specified in + this map to be selected; Labels within the + LabelSelector are OR'ed. + """ + + inclusion_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=501312642, + ) + + +class GlobalVmExtensionPolicyList(proto.Message): + r"""Response to list global VM extension policy resources. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + + This field is a member of `oneof`_ ``_etag``. + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1.types.GlobalVmExtensionPolicy]): + A list of GlobalVmExtensionPolicy resources. + kind (str): + Output only. Type of resource. + + This field is a member of `oneof`_ ``_kind``. + next_page_token (str): + [Output Only] This token allows you to get the next page of + results for list requests. If the number of results is + larger thanmaxResults, use the nextPageToken as a value for + the query parameter pageToken in the next list request. + Subsequent list requests will have their own nextPageToken + to continue paging through the results. + + This field is a member of `oneof`_ ``_next_page_token``. + self_link (str): + Output only. [Output Only] Server-defined URL for this + resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + Output only. [Output Only] Unreachable resources. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["GlobalVmExtensionPolicy"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="GlobalVmExtensionPolicy", + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + +class GlobalVmExtensionPolicyRolloutOperation(proto.Message): + r"""Represents the rollout operation + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + rollout_input (google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutInput): + Required. The rollout input which defines the + rollout plan. + + This field is a member of `oneof`_ ``_rollout_input``. + rollout_status (google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutStatus): + Output only. [Output Only] The rollout status of the policy. + + This field is a member of `oneof`_ ``_rollout_status``. + """ + + rollout_input: "GlobalVmExtensionPolicyRolloutOperationRolloutInput" = proto.Field( + proto.MESSAGE, + number=265745340, + optional=True, + message="GlobalVmExtensionPolicyRolloutOperationRolloutInput", + ) + rollout_status: "GlobalVmExtensionPolicyRolloutOperationRolloutStatus" = ( + proto.Field( + proto.MESSAGE, + number=476426816, + optional=True, + message="GlobalVmExtensionPolicyRolloutOperationRolloutStatus", + ) + ) + + +class GlobalVmExtensionPolicyRolloutOperationRolloutInput(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + conflict_behavior (str): + Optional. Specifies the behavior of the rollout if a + conflict is detected in a project during a rollout. This + only applies to ``insert`` and ``update`` methods. + + A conflict occurs in the following cases: + + - ``insert`` method: If the zonal policy already exists when + the insert happens. + - ``update`` method: If the zonal policy was modified by a + zonal API call outside of this rollout. + + Possible values are the following: + + - ``""`` (empty string): If a conflict occurs, the local + value is not overwritten. This is the default behavior. + - ``"overwrite"``: If a conflict occurs, the local value is + overwritten with the rollout value. + + This field is a member of `oneof`_ ``_conflict_behavior``. + name (str): + Optional. The name of the rollout plan. + Ex. + projects//locations/global/rolloutPlans/. + + This field is a member of `oneof`_ ``_name``. + predefined_rollout_plan (str): + Optional. Specifies the predefined rollout plan for the + policy. Valid values are ``SLOW_ROLLOUT`` and + ``FAST_ROLLOUT``. The recommended value is ``SLOW_ROLLOUT`` + for progressive rollout. For more information, see Rollout + plans for global policies. Check the PredefinedRolloutPlan + enum for the list of possible values. + + This field is a member of `oneof`_ ``_predefined_rollout_plan``. + retry_uuid (str): + Optional. The UUID that identifies a policy rollout retry + attempt for update and delete operations. Set this field + only when retrying a rollout for an existing extension + policy. + + - ``update`` method: Lets you retry policy rollout without + changes. An error occurs if you set retry_uuid but the + policy is modified. + - ``delete`` method: Lets you retry policy deletion rollout + if the previous deletion rollout is not finished and the + policy is in the DELETING state. If you set this field + when the policy is not in the DELETING state, an error + occurs. + + This field is a member of `oneof`_ ``_retry_uuid``. + """ + + class PredefinedRolloutPlan(proto.Enum): + r"""Optional. Specifies the predefined rollout plan for the policy. + Valid values are ``SLOW_ROLLOUT`` and ``FAST_ROLLOUT``. The + recommended value is ``SLOW_ROLLOUT`` for progressive rollout. For + more information, see Rollout plans for global policies. + + Values: + UNDEFINED_PREDEFINED_ROLLOUT_PLAN (0): + A value indicating that the enum field is not + set. + FAST_ROLLOUT (207153326): + No description available. + ROLLOUT_PLAN_UNSPECIFIED (144511983): + No description available. + SLOW_ROLLOUT (31032659): + No description available. + """ + + UNDEFINED_PREDEFINED_ROLLOUT_PLAN = 0 + FAST_ROLLOUT = 207153326 + ROLLOUT_PLAN_UNSPECIFIED = 144511983 + SLOW_ROLLOUT = 31032659 + + conflict_behavior: str = proto.Field( + proto.STRING, + number=115729439, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + predefined_rollout_plan: str = proto.Field( + proto.STRING, + number=364023440, + optional=True, + ) + retry_uuid: str = proto.Field( + proto.STRING, + number=472838898, + optional=True, + ) + + +class GlobalVmExtensionPolicyRolloutOperationRolloutStatus(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + current_rollouts (MutableSequence[google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata]): + Output only. [Output Only] The current rollouts for the + latest version of the resource. There should be only one + current rollout, but for scalability, we make it repeated. + previous_rollout (google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata): + Output only. [Output Only] The last completed rollout + resource. This field will not be populated until the first + rollout is completed. + + This field is a member of `oneof`_ ``_previous_rollout``. + """ + + current_rollouts: MutableSequence[ + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata" + ] = proto.RepeatedField( + proto.MESSAGE, + number=39829736, + message="GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata", + ) + previous_rollout: "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata" = proto.Field( + proto.MESSAGE, + number=375749737, + optional=True, + message="GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata", + ) + + +class GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadata( + proto.Message +): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location_rollout_status (MutableMapping[str, google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus]): + Output only. [Output Only] The rollout status for each + location. The list of the locations is the same as the list + of locations in the rollout plan. + rollout (str): + Output only. [Output Only] The name of the rollout. Ex. + projects//locations/global/rollouts/. + + This field is a member of `oneof`_ ``_rollout``. + rollout_plan (str): + Output only. [Output Only] The name of the rollout plan. Ex. + projects//locations/global/rolloutPlans/. + + This field is a member of `oneof`_ ``_rollout_plan``. + state (str): + Output only. [Output Only] The overall state of the rollout. + Check the State enum for the list of possible values. + + This field is a member of `oneof`_ ``_state``. + """ + + class State(proto.Enum): + r"""Output only. [Output Only] The overall state of the rollout. + + Values: + UNDEFINED_STATE (0): + A value indicating that the enum field is not + set. + STATE_CANCELLED (534636259): + Iteration was explicitly cancelled. + STATE_COMPLETED (265728989): + Iteration completed, with all actions being + successful. + STATE_FAILED (50857931): + Iteration completed, with failures. + STATE_PAUSED (337513660): + The rollout is paused. + STATE_PROCESSING (74195873): + Iteration is in progress. + STATE_UNKNOWN (230861404): + Impossible to determine current state of the + iteration. + STATE_UNSPECIFIED (470755401): + Default value. This value is unused. + """ + + UNDEFINED_STATE = 0 + STATE_CANCELLED = 534636259 + STATE_COMPLETED = 265728989 + STATE_FAILED = 50857931 + STATE_PAUSED = 337513660 + STATE_PROCESSING = 74195873 + STATE_UNKNOWN = 230861404 + STATE_UNSPECIFIED = 470755401 + + location_rollout_status: MutableMapping[ + str, + "GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus", + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=278036490, + message="GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus", + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + optional=True, + ) + rollout_plan: str = proto.Field( + proto.STRING, + number=459057399, + optional=True, + ) + state: str = proto.Field( + proto.STRING, + number=109757585, + optional=True, + ) + + +class GlobalVmExtensionPolicyRolloutOperationRolloutStatusRolloutMetadataLocationRolloutStatus( + proto.Message +): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + state (str): + Output only. [Output Only] The state of the location + rollout. Check the State enum for the list of possible + values. + + This field is a member of `oneof`_ ``_state``. + """ + + class State(proto.Enum): + r"""Output only. [Output Only] The state of the location rollout. + + Values: + UNDEFINED_STATE (0): + A value indicating that the enum field is not + set. + LOCATION_ROLLOUT_STATE_COMPLETED (134765221): + The location rollout is completed. + LOCATION_ROLLOUT_STATE_FAILED (53286403): + The location rollout has failed. + LOCATION_ROLLOUT_STATE_NOT_STARTED (471817423): + The location rollout has not started. + LOCATION_ROLLOUT_STATE_SKIPPED (54074890): + The location rollout is skipped. + LOCATION_ROLLOUT_STATE_UNSPECIFIED (242367761): + Default value. This value is unused. + """ + + UNDEFINED_STATE = 0 + LOCATION_ROLLOUT_STATE_COMPLETED = 134765221 + LOCATION_ROLLOUT_STATE_FAILED = 53286403 + LOCATION_ROLLOUT_STATE_NOT_STARTED = 471817423 + LOCATION_ROLLOUT_STATE_SKIPPED = 54074890 + LOCATION_ROLLOUT_STATE_UNSPECIFIED = 242367761 + + state: str = proto.Field( + proto.STRING, + number=109757585, + optional=True, + ) + + class GroupMaintenanceInfo(proto.Message): r"""Maintenance Info for ReservationBlocks. @@ -52953,7 +54235,7 @@ class ImageParams(proto.Message): Tag keys and values have the same definition as resource manager tags. Keys and values can be either in numeric format, such as ``tagKeys/{tag_key_id}`` and - ``tagValues/456`` or in namespaced format such as + ``tagValues/{tag_value_id}`` or in namespaced format such as ``{org_id|project_id}/{tag_key_short_name}`` and ``{tag_value_short_name}``. The field is ignored (both PUT & PATCH) when empty. @@ -53840,6 +55122,58 @@ class InsertGlobalPublicDelegatedPrefixeRequest(proto.Message): ) +class InsertGlobalVmExtensionPolicyRequest(proto.Message): + r"""A request message for GlobalVmExtensionPolicies.Insert. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + global_vm_extension_policy_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicy): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + global_vm_extension_policy_resource: "GlobalVmExtensionPolicy" = proto.Field( + proto.MESSAGE, + number=101542927, + message="GlobalVmExtensionPolicy", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + class InsertHealthCheckRequest(proto.Message): r"""A request message for HealthChecks.Insert. See the method description for details. @@ -57032,6 +58366,58 @@ class InsertResourcePolicyRequest(proto.Message): ) +class InsertRolloutPlanRequest(proto.Message): + r"""A request message for RolloutPlans.Insert. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout_plan_resource (google.cloud.compute_v1.types.RolloutPlan): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout_plan_resource: "RolloutPlan" = proto.Field( + proto.MESSAGE, + number=38629974, + message="RolloutPlan", + ) + + class InsertRouteRequest(proto.Message): r"""A request message for Routes.Insert. See the method description for details. @@ -60137,7 +61523,7 @@ class InstanceGroupManagerAggregatedList(proto.Message): Attributes: id (str): - Output only. [Output Only] Unique identifier for the + Output only. Unique identifier for the resource; defined by the server. This field is a member of `oneof`_ ``_id``. @@ -60145,29 +61531,32 @@ class InstanceGroupManagerAggregatedList(proto.Message): A list of InstanceGroupManagersScopedList resources. kind (str): - Output only. [Output Only] The resource type, which is - alwayscompute#instanceGroupManagerAggregatedList for an - aggregated list of managed instance groups. + Output only. The resource type, which is + alwayscompute#instanceGroupManagerAggregatedList + for an aggregated list of managed instance + groups. This field is a member of `oneof`_ ``_kind``. next_page_token (str): - Output only. [Output Only] This token allows you to get the - next page of results for list requests. If the number of - results is larger thanmaxResults, use the nextPageToken as a - value for the query parameter pageToken in the next list - request. Subsequent list requests will have their own - nextPageToken to continue paging through the results. + Output only. This token allows you to get the + next page of results for list requests. If the + number of results is larger thanmaxResults, use + the nextPageToken as a value for the query + parameter pageToken in the next list request. + Subsequent list requests will have their own + nextPageToken to continue paging through the + results. This field is a member of `oneof`_ ``_next_page_token``. self_link (str): - Output only. [Output Only] Server-defined URL for this + Output only. Server-defined URL for this resource. This field is a member of `oneof`_ ``_self_link``. unreachables (MutableSequence[str]): - Output only. [Output Only] Unreachable resources. + Output only. Unreachable resources. warning (google.cloud.compute_v1.types.Warning): - Output only. [Output Only] Informational warning message. + Output only. Informational warning message. This field is a member of `oneof`_ ``_warning``. """ @@ -60514,34 +61903,36 @@ class InstanceGroupManagerList(proto.Message): Attributes: id (str): - Output only. [Output Only] Unique identifier for the + Output only. Unique identifier for the resource; defined by the server. This field is a member of `oneof`_ ``_id``. items (MutableSequence[google.cloud.compute_v1.types.InstanceGroupManager]): A list of InstanceGroupManager resources. kind (str): - Output only. [Output Only] The resource type, which is - always compute#instanceGroupManagerList for a list of - managed instance groups. + Output only. The resource type, which is + always compute#instanceGroupManagerList for a + list of managed instance groups. This field is a member of `oneof`_ ``_kind``. next_page_token (str): - Output only. [Output Only] This token allows you to get the - next page of results for list requests. If the number of - results is larger thanmaxResults, use the nextPageToken as a - value for the query parameter pageToken in the next list - request. Subsequent list requests will have their own - nextPageToken to continue paging through the results. + Output only. This token allows you to get the + next page of results for list requests. If the + number of results is larger thanmaxResults, use + the nextPageToken as a value for the query + parameter pageToken in the next list request. + Subsequent list requests will have their own + nextPageToken to continue paging through the + results. This field is a member of `oneof`_ ``_next_page_token``. self_link (str): - Output only. [Output Only] Server-defined URL for this + Output only. Server-defined URL for this resource. This field is a member of `oneof`_ ``_self_link``. warning (google.cloud.compute_v1.types.Warning): - Output only. [Output Only] Informational warning message. + Output only. Informational warning message. This field is a member of `oneof`_ ``_warning``. """ @@ -60847,34 +62238,36 @@ class InstanceGroupManagerResizeRequestsListResponse(proto.Message): Attributes: id (str): - Output only. [Output Only] Unique identifier for the + Output only. Unique identifier for the resource; defined by the server. This field is a member of `oneof`_ ``_id``. items (MutableSequence[google.cloud.compute_v1.types.InstanceGroupManagerResizeRequest]): A list of resize request resources. kind (str): - Output only. [Output Only] Type of the resource. - Alwayscompute#instanceGroupManagerResizeRequestList for a - list of resize requests. + Output only. Type of the resource. + Alwayscompute#instanceGroupManagerResizeRequestList + for a list of resize requests. This field is a member of `oneof`_ ``_kind``. next_page_token (str): - Output only. [Output Only] This token allows you to get the - next page of results for list requests. If the number of - results is larger thanmaxResults, use the nextPageToken as a - value for the query parameter pageToken in the next list - request. Subsequent list requests will have their own - nextPageToken to continue paging through the results. + Output only. This token allows you to get the + next page of results for list requests. If the + number of results is larger than maxResults, use + thenextPageToken as a value for the query + parameterpageToken in the next list request. + Subsequent list requests will have their own + nextPageToken to continue paging through the + results. This field is a member of `oneof`_ ``_next_page_token``. self_link (str): - Output only. [Output Only] Server-defined URL for this + Output only. Server-defined URL for this resource. This field is a member of `oneof`_ ``_self_link``. warning (google.cloud.compute_v1.types.Warning): - Output only. [Output Only] Informational warning message. + Output only. Informational warning message. This field is a member of `oneof`_ ``_warning``. """ @@ -62378,11 +63771,13 @@ class InstanceGroupManagersScopedList(proto.Message): Attributes: instance_group_managers (MutableSequence[google.cloud.compute_v1.types.InstanceGroupManager]): - Output only. [Output Only] The list of managed instance - groups that are contained in the specified project and zone. + Output only. The list of managed instance + groups that are contained in the specified + project and zone. warning (google.cloud.compute_v1.types.Warning): - Output only. [Output Only] The warning that replaces the - list of managed instance groups when the list is empty. + Output only. The warning that replaces the + list of managed instance groups when the list is + empty. This field is a member of `oneof`_ ``_warning``. """ @@ -63190,7 +64585,7 @@ class InstanceParams(proto.Message): instance. Tag keys and values have the same definition as resource manager tags. Keys and values can be either in numeric format, such as ``tagKeys/{tag_key_id}`` and - ``tagValues/456`` or in namespaced format such as + ``tagValues/{tag_value_id}`` or in namespaced format such as ``{org_id|project_id}/{tag_key_short_name}`` and ``{tag_value_short_name}``. The field is ignored (both PUT & PATCH) when empty. @@ -63317,10 +64712,12 @@ class InstanceProperties(proto.Message): resource_manager_tags (MutableMapping[str, str]): Input only. Resource manager tags to be bound to the instance. Tag keys and values have the same definition as - resource manager tags. Keys must be in the format - ``tagKeys/{tag_key_id}``, and values are in the format - ``tagValues/456``. The field is ignored (both PUT & PATCH) - when empty. + resource manager tags. Keys and values can be either in + numeric format, such as ``tagKeys/{tag_key_id}`` and + ``tagValues/{tag_value_id}`` or in namespaced format such as + ``{org_id|project_id}/{tag_key_short_name}`` and + ``{tag_value_short_name}``. The field is ignored (both PUT & + PATCH) when empty. resource_policies (MutableSequence[str]): Resource policies (names, not URLs) applied to instances created from these properties. @@ -69820,7 +71217,7 @@ class IntentMismatchBehavior(proto.Enum): class InterconnectGroupsCreateMembersInterconnectInput(proto.Message): - r"""LINT.IfChange + r""" .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -72438,6 +73835,15 @@ class LicenseCode(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + allowed_replacement_licenses (MutableSequence[str]): + Specifies licenseCodes of licenses that can replace this + license. Note: such replacements are allowed even if + removable_from_disk is false. + appendable_to_disk (bool): + If true, this license can be appended to an + existing disk's set of licenses. + + This field is a member of `oneof`_ ``_appendable_to_disk``. creation_timestamp (str): Output only. [Output Only] Creation timestamp inRFC3339 text format. @@ -72452,6 +73858,11 @@ class LicenseCode(proto.Message): resource. This identifier is defined by the server. This field is a member of `oneof`_ ``_id``. + incompatible_licenses (MutableSequence[str]): + Specifies licenseCodes of licenses that are + incompatible with this license. If a license is + incompatible with this license, it cannot be + attached to the same disk or image. kind (str): Output only. [Output Only] Type of resource. Always compute#licenseCode for licenses. @@ -72460,16 +73871,50 @@ class LicenseCode(proto.Message): license_alias (MutableSequence[google.cloud.compute_v1.types.LicenseCodeLicenseAlias]): [Output Only] URL and description aliases of Licenses with the same License Code. + minimum_retention (google.cloud.compute_v1.types.Duration): + If set, this license will be unable to be removed or + replaced once attached to a disk until the minimum_retention + period has passed. + + This field is a member of `oneof`_ ``_minimum_retention``. + multi_tenant_only (bool): + If true, this license can only be used on VMs + on multi tenant nodes. + + This field is a member of `oneof`_ ``_multi_tenant_only``. name (str): Output only. [Output Only] Name of the resource. The name is 1-20 characters long and must be a valid 64 bit integer. This field is a member of `oneof`_ ``_name``. + os_license (bool): + If true, indicates this is an OS license. + Only one OS license can be attached to a disk or + image at a time. + + This field is a member of `oneof`_ ``_os_license``. + removable_from_disk (bool): + If true, this license can be removed from a + disk's set of licenses, with no replacement + license needed. + + This field is a member of `oneof`_ ``_removable_from_disk``. + required_coattached_licenses (MutableSequence[str]): + Specifies the set of permissible coattached + licenseCodes of licenses that satisfy the + coattachment requirement of this license. At + least one license from the set must be attached + to the same disk or image as this license. self_link (str): Output only. [Output Only] Server-defined URL for the resource. This field is a member of `oneof`_ ``_self_link``. + sole_tenant_only (bool): + If true, this license can only be used on VMs + on sole tenant nodes. + + This field is a member of `oneof`_ ``_sole_tenant_only``. state (str): Output only. [Output Only] Current state of this License Code. Check the State enum for the list of possible values. @@ -72481,6 +73926,11 @@ class LicenseCode(proto.Message): Otherwise, the license is not transferred. This field is a member of `oneof`_ ``_transferable``. + update_timestamp (str): + Output only. [Output Only] Last update timestamp inRFC3339 + text format. + + This field is a member of `oneof`_ ``_update_timestamp``. """ class State(proto.Enum): @@ -72513,6 +73963,15 @@ class State(proto.Enum): STATE_UNSPECIFIED = 470755401 TERMINATED = 250018339 + allowed_replacement_licenses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=195677718, + ) + appendable_to_disk: bool = proto.Field( + proto.BOOL, + number=16959254, + optional=True, + ) creation_timestamp: str = proto.Field( proto.STRING, number=30525366, @@ -72528,6 +73987,10 @@ class State(proto.Enum): number=3355, optional=True, ) + incompatible_licenses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=334239768, + ) kind: str = proto.Field( proto.STRING, number=3292052, @@ -72538,16 +74001,46 @@ class State(proto.Enum): number=43550930, message="LicenseCodeLicenseAlias", ) + minimum_retention: "Duration" = proto.Field( + proto.MESSAGE, + number=155398189, + optional=True, + message="Duration", + ) + multi_tenant_only: bool = proto.Field( + proto.BOOL, + number=274395163, + optional=True, + ) name: str = proto.Field( proto.STRING, number=3373707, optional=True, ) + os_license: bool = proto.Field( + proto.BOOL, + number=487986406, + optional=True, + ) + removable_from_disk: bool = proto.Field( + proto.BOOL, + number=25854638, + optional=True, + ) + required_coattached_licenses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=129195265, + ) self_link: str = proto.Field( proto.STRING, number=456214797, optional=True, ) + sole_tenant_only: bool = proto.Field( + proto.BOOL, + number=427525559, + optional=True, + ) state: str = proto.Field( proto.STRING, number=109757585, @@ -72558,6 +74051,11 @@ class State(proto.Enum): number=4349893, optional=True, ) + update_timestamp: str = proto.Field( + proto.STRING, + number=120894752, + optional=True, + ) class LicenseCodeLicenseAlias(proto.Message): @@ -72598,7 +74096,7 @@ class LicenseParams(proto.Message): license. Tag keys and values have the same definition as resource manager tags. Keys and values can be either in numeric format, such as ``tagKeys/{tag_key_id}`` and - ``tagValues/456`` or in namespaced format such as + ``tagValues/{tag_value_id}`` or in namespaced format such as ``{org_id|project_id}/{tag_key_short_name}`` and ``{tag_value_short_name}``. The field is ignored (both PUT & PATCH) when empty. @@ -76939,9 +78437,9 @@ class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): ) -class ListHealthChecksRequest(proto.Message): - r"""A request message for HealthChecks.List. See the method - description for details. +class ListGlobalVmExtensionPoliciesRequest(proto.Message): + r"""A request message for GlobalVmExtensionPolicies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -77096,9 +78594,9 @@ class ListHealthChecksRequest(proto.Message): ) -class ListImagesRequest(proto.Message): - r"""A request message for Images.List. See the method description - for details. +class ListHealthChecksRequest(proto.Message): + r"""A request message for HealthChecks.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -77253,10 +78751,167 @@ class ListImagesRequest(proto.Message): ) -class ListInstanceGroupManagerResizeRequestsRequest(proto.Message): - r"""A request message for - InstanceGroupManagerResizeRequests.List. See the method - description for details. +class ListImagesRequest(proto.Message): + r"""A request message for Images.List. See the method description + for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: + + :: + + labels.owner:* + + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. + + To filter on multiple expressions, provide each separate + expression within parentheses. For example: + + :: + + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") + + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + + :: + + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListInstanceGroupManagerResizeRequestsRequest(proto.Message): + r"""A request message for + InstanceGroupManagerResizeRequests.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -90340,9 +91995,9 @@ class ListResourcePoliciesRequest(proto.Message): ) -class ListRoutePoliciesRoutersRequest(proto.Message): - r"""A request message for Routers.ListRoutePolicies. See the - method description for details. +class ListRolloutPlansRequest(proto.Message): + r"""A request message for RolloutPlans.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -90453,8 +92108,6 @@ class ListRoutePoliciesRoutersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -90466,9 +92119,6 @@ class ListRoutePoliciesRoutersRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - router (str): - Name or id of the resource for this request. - Name should conform to RFC1035. """ filter: str = proto.Field( @@ -90495,23 +92145,15 @@ class ListRoutePoliciesRoutersRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - router: str = proto.Field( - proto.STRING, - number=148608841, - ) -class ListRoutersRequest(proto.Message): - r"""A request message for Routers.List. See the method +class ListRolloutsRequest(proto.Message): + r"""A request message for Rollouts.List. See the method description for details. @@ -90623,8 +92265,6 @@ class ListRoutersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -90662,10 +92302,6 @@ class ListRoutersRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -90673,9 +92309,9 @@ class ListRoutersRequest(proto.Message): ) -class ListRoutesRequest(proto.Message): - r"""A request message for Routes.List. See the method description - for details. +class ListRoutePoliciesRoutersRequest(proto.Message): + r"""A request message for Routers.ListRoutePolicies. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -90786,6 +92422,8 @@ class ListRoutesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -90797,6 +92435,9 @@ class ListRoutesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + router (str): + Name or id of the resource for this request. + Name should conform to RFC1035. """ filter: str = proto.Field( @@ -90823,15 +92464,23 @@ class ListRoutesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + router: str = proto.Field( + proto.STRING, + number=148608841, + ) -class ListSecurityPoliciesRequest(proto.Message): - r"""A request message for SecurityPolicies.List. See the method +class ListRoutersRequest(proto.Message): + r"""A request message for Routers.List. See the method description for details. @@ -90943,6 +92592,8 @@ class ListSecurityPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -90980,6 +92631,10 @@ class ListSecurityPoliciesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -90987,9 +92642,9 @@ class ListSecurityPoliciesRequest(proto.Message): ) -class ListServiceAttachmentsRequest(proto.Message): - r"""A request message for ServiceAttachments.List. See the method - description for details. +class ListRoutesRequest(proto.Message): + r"""A request message for Routes.List. See the method description + for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -91100,8 +92755,6 @@ class ListServiceAttachmentsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -91139,10 +92792,6 @@ class ListServiceAttachmentsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -91150,8 +92799,8 @@ class ListServiceAttachmentsRequest(proto.Message): ) -class ListSnapshotsRequest(proto.Message): - r"""A request message for Snapshots.List. See the method +class ListSecurityPoliciesRequest(proto.Message): + r"""A request message for SecurityPolicies.List. See the method description for details. @@ -91307,8 +92956,8 @@ class ListSnapshotsRequest(proto.Message): ) -class ListSslCertificatesRequest(proto.Message): - r"""A request message for SslCertificates.List. See the method +class ListServiceAttachmentsRequest(proto.Message): + r"""A request message for ServiceAttachments.List. See the method description for details. @@ -91420,6 +93069,8 @@ class ListSslCertificatesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -91457,6 +93108,10 @@ class ListSslCertificatesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -91464,8 +93119,8 @@ class ListSslCertificatesRequest(proto.Message): ) -class ListSslPoliciesRequest(proto.Message): - r"""A request message for SslPolicies.List. See the method +class ListSnapshotsRequest(proto.Message): + r"""A request message for Snapshots.List. See the method description for details. @@ -91621,8 +93276,8 @@ class ListSslPoliciesRequest(proto.Message): ) -class ListStoragePoolTypesRequest(proto.Message): - r"""A request message for StoragePoolTypes.List. See the method +class ListSslCertificatesRequest(proto.Message): + r"""A request message for SslCertificates.List. See the method description for details. @@ -91745,8 +93400,6 @@ class ListStoragePoolTypesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -91778,14 +93431,10 @@ class ListStoragePoolTypesRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListStoragePoolsRequest(proto.Message): - r"""A request message for StoragePools.List. See the method +class ListSslPoliciesRequest(proto.Message): + r"""A request message for SslPolicies.List. See the method description for details. @@ -91908,8 +93557,6 @@ class ListStoragePoolsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -91941,14 +93588,10 @@ class ListStoragePoolsRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListSubnetworksRequest(proto.Message): - r"""A request message for Subnetworks.List. See the method +class ListStoragePoolTypesRequest(proto.Message): + r"""A request message for StoragePoolTypes.List. See the method description for details. @@ -92060,8 +93703,6 @@ class ListSubnetworksRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -92073,42 +93714,172 @@ class ListSubnetworksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - views (str): - Defines the extra views returned back in the subnetwork - resource. Supported values: + zone (str): + The name of the zone for this request. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class ListStoragePoolsRequest(proto.Message): + r"""A request message for StoragePools.List. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: :: - - WITH_UTILIZATION: Utilization data is included in the - response. + labels.owner:* - Check the Views enum for the list of possible values. + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. - This field is a member of `oneof`_ ``_views``. - """ + To filter on multiple expressions, provide each separate + expression within parentheses. For example: - class Views(proto.Enum): - r"""Defines the extra views returned back in the subnetwork resource. - Supported values: + :: - :: + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") - - WITH_UTILIZATION: Utilization data is included in the - response. + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: - Values: - UNDEFINED_VIEWS (0): - A value indicating that the enum field is not - set. - DEFAULT (115302945): - No description available. - WITH_UTILIZATION (504090633): - Utilization data is included in the response. - """ + :: - UNDEFINED_VIEWS = 0 - DEFAULT = 115302945 - WITH_UTILIZATION = 504090633 + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. + """ filter: str = proto.Field( proto.STRING, @@ -92134,24 +93905,19 @@ class Views(proto.Enum): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - views: str = proto.Field( + zone: str = proto.Field( proto.STRING, - number=112204398, - optional=True, + number=3744684, ) -class ListTargetGrpcProxiesRequest(proto.Message): - r"""A request message for TargetGrpcProxies.List. See the method +class ListSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.List. See the method description for details. @@ -92263,6 +94029,8 @@ class ListTargetGrpcProxiesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -92274,8 +94042,43 @@ class ListTargetGrpcProxiesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + views (str): + Defines the extra views returned back in the subnetwork + resource. Supported values: + + :: + + - WITH_UTILIZATION: Utilization data is included in the + response. + + Check the Views enum for the list of possible values. + + This field is a member of `oneof`_ ``_views``. """ + class Views(proto.Enum): + r"""Defines the extra views returned back in the subnetwork resource. + Supported values: + + :: + + - WITH_UTILIZATION: Utilization data is included in the + response. + + Values: + UNDEFINED_VIEWS (0): + A value indicating that the enum field is not + set. + DEFAULT (115302945): + No description available. + WITH_UTILIZATION (504090633): + Utilization data is included in the response. + """ + + UNDEFINED_VIEWS = 0 + DEFAULT = 115302945 + WITH_UTILIZATION = 504090633 + filter: str = proto.Field( proto.STRING, number=336120696, @@ -92300,15 +94103,24 @@ class ListTargetGrpcProxiesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + views: str = proto.Field( + proto.STRING, + number=112204398, + optional=True, + ) -class ListTargetHttpProxiesRequest(proto.Message): - r"""A request message for TargetHttpProxies.List. See the method +class ListTargetGrpcProxiesRequest(proto.Message): + r"""A request message for TargetGrpcProxies.List. See the method description for details. @@ -92464,8 +94276,8 @@ class ListTargetHttpProxiesRequest(proto.Message): ) -class ListTargetHttpsProxiesRequest(proto.Message): - r"""A request message for TargetHttpsProxies.List. See the method +class ListTargetHttpProxiesRequest(proto.Message): + r"""A request message for TargetHttpProxies.List. See the method description for details. @@ -92621,8 +94433,8 @@ class ListTargetHttpsProxiesRequest(proto.Message): ) -class ListTargetInstancesRequest(proto.Message): - r"""A request message for TargetInstances.List. See the method +class ListTargetHttpsProxiesRequest(proto.Message): + r"""A request message for TargetHttpsProxies.List. See the method description for details. @@ -92745,8 +94557,6 @@ class ListTargetInstancesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone scoping this request. """ filter: str = proto.Field( @@ -92778,14 +94588,10 @@ class ListTargetInstancesRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListTargetPoolsRequest(proto.Message): - r"""A request message for TargetPools.List. See the method +class ListTargetInstancesRequest(proto.Message): + r"""A request message for TargetInstances.List. See the method description for details. @@ -92897,8 +94703,6 @@ class ListTargetPoolsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -92910,6 +94714,8 @@ class ListTargetPoolsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone scoping this request. """ filter: str = proto.Field( @@ -92936,19 +94742,19 @@ class ListTargetPoolsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListTargetSslProxiesRequest(proto.Message): - r"""A request message for TargetSslProxies.List. See the method +class ListTargetPoolsRequest(proto.Message): + r"""A request message for TargetPools.List. See the method description for details. @@ -93060,6 +94866,8 @@ class ListTargetSslProxiesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -93097,6 +94905,10 @@ class ListTargetSslProxiesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -93104,8 +94916,8 @@ class ListTargetSslProxiesRequest(proto.Message): ) -class ListTargetTcpProxiesRequest(proto.Message): - r"""A request message for TargetTcpProxies.List. See the method +class ListTargetSslProxiesRequest(proto.Message): + r"""A request message for TargetSslProxies.List. See the method description for details. @@ -93261,8 +95073,8 @@ class ListTargetTcpProxiesRequest(proto.Message): ) -class ListTargetVpnGatewaysRequest(proto.Message): - r"""A request message for TargetVpnGateways.List. See the method +class ListTargetTcpProxiesRequest(proto.Message): + r"""A request message for TargetTcpProxies.List. See the method description for details. @@ -93374,8 +95186,6 @@ class ListTargetVpnGatewaysRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -93413,10 +95223,6 @@ class ListTargetVpnGatewaysRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -93424,8 +95230,8 @@ class ListTargetVpnGatewaysRequest(proto.Message): ) -class ListUrlMapsRequest(proto.Message): - r"""A request message for UrlMaps.List. See the method +class ListTargetVpnGatewaysRequest(proto.Message): + r"""A request message for TargetVpnGateways.List. See the method description for details. @@ -93537,6 +95343,8 @@ class ListUrlMapsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -93574,6 +95382,10 @@ class ListUrlMapsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -93581,9 +95393,9 @@ class ListUrlMapsRequest(proto.Message): ) -class ListUsableBackendBucketsRequest(proto.Message): - r"""A request message for BackendBuckets.ListUsable. See the - method description for details. +class ListUrlMapsRequest(proto.Message): + r"""A request message for UrlMaps.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -93738,8 +95550,8 @@ class ListUsableBackendBucketsRequest(proto.Message): ) -class ListUsableBackendServicesRequest(proto.Message): - r"""A request message for BackendServices.ListUsable. See the +class ListUsableBackendBucketsRequest(proto.Message): + r"""A request message for BackendBuckets.ListUsable. See the method description for details. @@ -93895,9 +95707,9 @@ class ListUsableBackendServicesRequest(proto.Message): ) -class ListUsableRegionBackendBucketsRequest(proto.Message): - r"""A request message for RegionBackendBuckets.ListUsable. See - the method description for details. +class ListUsableBackendServicesRequest(proto.Message): + r"""A request message for BackendServices.ListUsable. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -94008,10 +95820,6 @@ class ListUsableRegionBackendBucketsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. - It must be a string that meets the requirements - in RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -94049,10 +95857,6 @@ class ListUsableRegionBackendBucketsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -94060,8 +95864,8 @@ class ListUsableRegionBackendBucketsRequest(proto.Message): ) -class ListUsableRegionBackendServicesRequest(proto.Message): - r"""A request message for RegionBackendServices.ListUsable. See +class ListUsableRegionBackendBucketsRequest(proto.Message): + r"""A request message for RegionBackendBuckets.ListUsable. See the method description for details. @@ -94225,178 +96029,9 @@ class ListUsableRegionBackendServicesRequest(proto.Message): ) -class ListUsableSubnetworksRequest(proto.Message): - r"""A request message for Subnetworks.ListUsable. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - filter (str): - A filter expression that filters resources listed in the - response. Most Compute resources support two types of filter - expressions: expressions that support regular expressions - and expressions that follow API improvement proposal - AIP-160. These two types of filter expressions cannot be - mixed in one request. - - If you want to use AIP-160, your expression must specify the - field name, an operator, and the value that you want to use - for filtering. The value must be a string, a number, or a - boolean. The operator must be either ``=``, ``!=``, ``>``, - ``<``, ``<=``, ``>=`` or ``:``. - - For example, if you are filtering Compute Engine instances, - you can exclude instances named ``example-instance`` by - specifying ``name != example-instance``. - - The ``:*`` comparison can be used to test whether a key has - been defined. For example, to find all objects with - ``owner`` label use: - - :: - - labels.owner:* - - You can also filter nested fields. For example, you could - specify ``scheduling.automaticRestart = false`` to include - instances only if they are not scheduled for automatic - restarts. You can use filtering on nested fields to filter - based onresource labels. - - To filter on multiple expressions, provide each separate - expression within parentheses. For example: - - :: - - (scheduling.automaticRestart = true) - (cpuPlatform = "Intel Skylake") - - By default, each expression is an ``AND`` expression. - However, you can include ``AND`` and ``OR`` expressions - explicitly. For example: - - :: - - (cpuPlatform = "Intel Skylake") OR - (cpuPlatform = "Intel Broadwell") AND - (scheduling.automaticRestart = true) - - If you want to use a regular expression, use the ``eq`` - (equal) or ``ne`` (not equal) operator against a single - un-parenthesized expression with or without quotes or - against multiple parenthesized expressions. Examples: - - ``fieldname eq unquoted literal`` - ``fieldname eq 'single quoted literal'`` - ``fieldname eq "double quoted literal"`` - ``(fieldname1 eq literal) (fieldname2 ne "literal")`` - - The literal value is interpreted as a regular expression - using GoogleRE2 library syntax. The literal value must match - the entire field. - - For example, to filter for instances that do not end with - name "instance", you would use ``name ne .*instance``. - - You cannot combine constraints on multiple fields using - regular expressions. - - This field is a member of `oneof`_ ``_filter``. - max_results (int): - The maximum number of results per page that should be - returned. If the number of available results is larger than - ``maxResults``, Compute Engine returns a ``nextPageToken`` - that can be used to get the next page of results in - subsequent list requests. Acceptable values are ``0`` to - ``500``, inclusive. (Default: ``500``) - - This field is a member of `oneof`_ ``_max_results``. - order_by (str): - Sorts list results by a certain order. By default, results - are returned in alphanumerical order based on the resource - name. - - You can also sort results in descending order based on the - creation timestamp using - ``orderBy="creationTimestamp desc"``. This sorts results - based on the ``creationTimestamp`` field in reverse - chronological order (newest result first). Use this to sort - resources like operations so that the newest operation is - returned first. - - Currently, only sorting by ``name`` or - ``creationTimestamp desc`` is supported. - - This field is a member of `oneof`_ ``_order_by``. - page_token (str): - Specifies a page token to use. Set ``pageToken`` to the - ``nextPageToken`` returned by a previous list request to get - the next page of results. - - This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. - return_partial_success (bool): - Opt-in for partial success behavior which - provides partial results in case of failure. The - default value is false. - - For example, when partial success behavior is - enabled, aggregatedList for a single zone scope - either returns all resources in the zone or no - resources, with an error code. - - This field is a member of `oneof`_ ``_return_partial_success``. - service_project (str): - The project id or project number in which the subnetwork is - intended to be used. Only applied for Shared VPC. See - `Shared VPC - documentation `__ - - This field is a member of `oneof`_ ``_service_project``. - """ - - filter: str = proto.Field( - proto.STRING, - number=336120696, - optional=True, - ) - max_results: int = proto.Field( - proto.UINT32, - number=54715419, - optional=True, - ) - order_by: str = proto.Field( - proto.STRING, - number=160562920, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=19994697, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, - optional=True, - ) - service_project: str = proto.Field( - proto.STRING, - number=530592655, - optional=True, - ) - - -class ListVpnGatewaysRequest(proto.Message): - r"""A request message for VpnGateways.List. See the method - description for details. +class ListUsableRegionBackendServicesRequest(proto.Message): + r"""A request message for RegionBackendServices.ListUsable. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -94508,7 +96143,341 @@ class ListVpnGatewaysRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. + It must be a string that meets the requirements + in RFC1035. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListUsableSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.ListUsable. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: + + :: + + labels.owner:* + + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. + + To filter on multiple expressions, provide each separate + expression within parentheses. For example: + + :: + + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") + + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + + :: + + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + service_project (str): + The project id or project number in which the subnetwork is + intended to be used. Only applied for Shared VPC. See + `Shared VPC + documentation `__ + + This field is a member of `oneof`_ ``_service_project``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + service_project: str = proto.Field( + proto.STRING, + number=530592655, + optional=True, + ) + + +class ListVpnGatewaysRequest(proto.Message): + r"""A request message for VpnGateways.List. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: + + :: + + labels.owner:* + + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. + + To filter on multiple expressions, provide each separate + expression within parentheses. For example: + + :: + + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") + + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + + :: + + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -100773,9 +102742,15 @@ class DeleteStatus(proto.Enum): consensus peering connection can be deleted. DELETE_STATUS_UNSPECIFIED (395396446): No description available. + LOCAL_CANCEL_REQUESTED (169545277): + The local network admin requested to cancel their delete + request after DELETE_ACKNOWLEDGED. LOCAL_DELETE_REQUESTED (227335214): Network admin has requested deletion of this peering connection. + PEER_CANCEL_REQUESTED (140057862): + The peer network admin requested to cancel their delete + request after DELETE_ACKNOWLEDGED. PEER_DELETE_REQUESTED (197847799): The peer network admin has requested deletion of this peering connection. @@ -100784,7 +102759,9 @@ class DeleteStatus(proto.Enum): UNDEFINED_DELETE_STATUS = 0 DELETE_ACKNOWLEDGED = 325293916 DELETE_STATUS_UNSPECIFIED = 395396446 + LOCAL_CANCEL_REQUESTED = 169545277 LOCAL_DELETE_REQUESTED = 227335214 + PEER_CANCEL_REQUESTED = 140057862 PEER_DELETE_REQUESTED = 197847799 class UpdateStatus(proto.Enum): @@ -101868,12 +103845,15 @@ class FirewallPolicyTypes(proto.Enum): set. RDMA_ROCE_POLICY (148757145): No description available. + ULL_POLICY (100494364): + No description available. VPC_POLICY (74319208): No description available. """ UNDEFINED_FIREWALL_POLICY_TYPES = 0 RDMA_ROCE_POLICY = 148757145 + ULL_POLICY = 100494364 VPC_POLICY = 74319208 class InterfaceTypes(proto.Enum): @@ -102699,6 +104679,26 @@ class NetworksAddPeeringRequest(proto.Message): ) +class NetworksCancelRequestRemovePeeringRequest(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name of the peering, which should conform to + RFC1035. + + This field is a member of `oneof`_ ``_name``. + """ + + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + + class NetworksGetEffectiveFirewallsResponse(proto.Message): r""" @@ -115447,34 +117447,37 @@ class RegionInstanceGroupManagerList(proto.Message): Attributes: id (str): - Output only. [Output Only] Unique identifier for the + Output only. Unique identifier for the resource; defined by the server. This field is a member of `oneof`_ ``_id``. items (MutableSequence[google.cloud.compute_v1.types.InstanceGroupManager]): A list of InstanceGroupManager resources. kind (str): - Output only. [Output Only] The resource type, which is - always compute#instanceGroupManagerList for a list of - managed instance groups that exist in th regional scope. + Output only. The resource type, which is + always compute#instanceGroupManagerList for a + list of managed instance groups that exist in th + regional scope. This field is a member of `oneof`_ ``_kind``. next_page_token (str): - Output only. [Output Only] This token allows you to get the - next page of results for list requests. If the number of - results is larger thanmaxResults, use the nextPageToken as a - value for the query parameter pageToken in the next list - request. Subsequent list requests will have their own - nextPageToken to continue paging through the results. + Output only. This token allows you to get the + next page of results for list requests. If the + number of results is larger thanmaxResults, use + the nextPageToken as a value for the query + parameter pageToken in the next list request. + Subsequent list requests will have their own + nextPageToken to continue paging through the + results. This field is a member of `oneof`_ ``_next_page_token``. self_link (str): - Output only. [Output Only] Server-defined URL for this + Output only. Server-defined URL for this resource. This field is a member of `oneof`_ ``_self_link``. warning (google.cloud.compute_v1.types.Warning): - Output only. [Output Only] Informational warning message. + Output only. Informational warning message. This field is a member of `oneof`_ ``_warning``. """ @@ -115542,37 +117545,39 @@ class RegionInstanceGroupManagerResizeRequestsListResponse(proto.Message): This field is a member of `oneof`_ ``_etag``. id (str): - Output only. [Output Only] Unique identifier for the + Output only. Unique identifier for the resource; defined by the server. This field is a member of `oneof`_ ``_id``. items (MutableSequence[google.cloud.compute_v1.types.InstanceGroupManagerResizeRequest]): A list of Resize Request resources. kind (str): - Output only. [Output Only] Type of the resource. + Output only. Type of the resource. Alwayscompute#regionInstanceGroupManagerResizeRequestList for a list of Resize Requests. This field is a member of `oneof`_ ``_kind``. next_page_token (str): - Output only. [Output Only] This token allows you to get the - next page of results for list requests. If the number of - results is larger thanmaxResults, use the nextPageToken as a - value for the query parameter pageToken in the next list - request. Subsequent list requests will have their own - nextPageToken to continue paging through the results. + Output only. This token allows you to get the + next page of results for list requests. If the + number of results is larger thanmaxResults, use + the nextPageToken as a value for the query + parameter pageToken in the next list request. + Subsequent list requests will have their own + nextPageToken to continue paging through the + results. This field is a member of `oneof`_ ``_next_page_token``. self_link (str): - Output only. [Output Only] Server-defined URL for this + Output only. Server-defined URL for this resource. This field is a member of `oneof`_ ``_self_link``. unreachables (MutableSequence[str]): - Output only. [Output Only] Unreachable resources. - end_interface: MixerListResponseWithEtagBuilder + Output only. Unreachable resources. end_interface: + MixerListResponseWithEtagBuilder warning (google.cloud.compute_v1.types.Warning): - Output only. [Output Only] Informational warning message. + Output only. Informational warning message. This field is a member of `oneof`_ ``_warning``. """ @@ -122453,6 +124458,1167 @@ class ResumeInstancesRegionInstanceGroupManagerRequest(proto.Message): ) +class Rollout(proto.Message): + r"""Rollout resource. + + A Rollout is a specific instance of a RolloutPlan. It represents + a single execution of a strategy to roll out a specific + resource. It also provides APIs to interact with the rollout. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cancellation_time (str): + Output only. The timestamp at which the + Rollout was cancelled. + + This field is a member of `oneof`_ ``_cancellation_time``. + completion_time (str): + Output only. The timestamp at which the + Rollout was completed. + + This field is a member of `oneof`_ ``_completion_time``. + creation_timestamp (str): + Output only. [Output Only] Creation timestamp inRFC3339 text + format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + current_wave_number (int): + Output only. The number of the currently + running wave. Ex. 1 + + This field is a member of `oneof`_ ``_current_wave_number``. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + + This field is a member of `oneof`_ ``_description``. + etag (str): + Output only. etag of the Rollout + Ex. abc1234 + + This field is a member of `oneof`_ ``_etag``. + id (int): + Output only. [Output Only] The unique identifier for the + resource. This identifier is defined by the server. + + This field is a member of `oneof`_ ``_id``. + kind (str): + Output only. [Output Only] Type of the resource. Always + compute#rollout for rollouts. + + This field is a member of `oneof`_ ``_kind``. + name (str): + Name of the resource. Provided by the client when the + resource is created. The name must be 1-63 characters long, + and comply withRFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + + This field is a member of `oneof`_ ``_name``. + rollout_entity (google.cloud.compute_v1.types.RolloutRolloutEntity): + Required. The resource being rolled out. + + This field is a member of `oneof`_ ``_rollout_entity``. + rollout_plan (str): + Required. Rollout Plan used to model the + Rollout. Ex. + compute.googleapis.com/v1/projects/1234/rolloutPlans/rp1 + + This field is a member of `oneof`_ ``_rollout_plan``. + self_link (str): + Output only. [Output Only] Server-defined fully-qualified + URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + Output only. [Output Only] Server-defined URL for this + resource's resource id. + + This field is a member of `oneof`_ ``_self_link_with_id``. + state (str): + Output only. The current state of the + Rollout. Check the State enum for the list of + possible values. + + This field is a member of `oneof`_ ``_state``. + wave_details (MutableSequence[google.cloud.compute_v1.types.RolloutWaveDetails]): + Output only. Details about each wave of the + rollout. + """ + + class State(proto.Enum): + r"""Output only. The current state of the Rollout. + + Values: + UNDEFINED_STATE (0): + A value indicating that the enum field is not + set. + CANCELLED (41957681): + The rollout is in a failure terminal state. + CANCELLING (226950512): + The rollout is being cancelled. + CANCEL_FAILED (389121442): + An attempted cancel operation was + unsuccessful. + COMPLETED (309921323): + The rollout is in a successful terminal + state. + COMPLETE_FAILED (188367363): + An attempted complete operation was + unsuccessful. + COMPLETING (480759734): + The rollout is being marked as completed. + FAILED (455706685): + The rollout completed with failures. + PAUSED (205491502): + The rollout is paused. + PAUSE_FAILED (7486150): + An attempted pause operation was + unsuccessful. + PAUSING (464660755): + The rollout is being paused. + PROCESSING (370416403): + A wave is being processed by the product. + READY (77848963): + The rollout has been successfully initialized + and is ready to start. + RESUMING (446856618): + The rollout is being resumed after being + paused. + ROLLBACK_WAVE_FAILED (326793064): + An attempted rollback operation failed to + complete successfully. + ROLLING_BACK (259411649): + A wave rollback is in progress for this + rollout. + STATE_UNSPECIFIED (470755401): + Undefined default state. Should never be + exposed to users. + UNINITIALIZED (327337595): + The rollout has been created but is not yet + ready to be started. + WAVE_FAILED (195452995): + The product failed to process the wave. + """ + + UNDEFINED_STATE = 0 + CANCELLED = 41957681 + CANCELLING = 226950512 + CANCEL_FAILED = 389121442 + COMPLETED = 309921323 + COMPLETE_FAILED = 188367363 + COMPLETING = 480759734 + FAILED = 455706685 + PAUSED = 205491502 + PAUSE_FAILED = 7486150 + PAUSING = 464660755 + PROCESSING = 370416403 + READY = 77848963 + RESUMING = 446856618 + ROLLBACK_WAVE_FAILED = 326793064 + ROLLING_BACK = 259411649 + STATE_UNSPECIFIED = 470755401 + UNINITIALIZED = 327337595 + WAVE_FAILED = 195452995 + + cancellation_time: str = proto.Field( + proto.STRING, + number=323792009, + optional=True, + ) + completion_time: str = proto.Field( + proto.STRING, + number=122892624, + optional=True, + ) + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + current_wave_number: int = proto.Field( + proto.INT64, + number=178280841, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: int = proto.Field( + proto.UINT64, + number=3355, + optional=True, + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + rollout_entity: "RolloutRolloutEntity" = proto.Field( + proto.MESSAGE, + number=70633009, + optional=True, + message="RolloutRolloutEntity", + ) + rollout_plan: str = proto.Field( + proto.STRING, + number=459057399, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + self_link_with_id: str = proto.Field( + proto.STRING, + number=44520962, + optional=True, + ) + state: str = proto.Field( + proto.STRING, + number=109757585, + optional=True, + ) + wave_details: MutableSequence["RolloutWaveDetails"] = proto.RepeatedField( + proto.MESSAGE, + number=8266492, + message="RolloutWaveDetails", + ) + + +class RolloutPlan(proto.Message): + r"""RolloutPlan resource. + + A RolloutPlan is the customer-defined strategy to divide a + large-scale change into smaller increments, referred to as + "waves". Each wave targets a specific portion of the overall + affected area and defines criteria that must be met before + progressing to the subsequent wave. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + creation_timestamp (str): + Output only. [Output Only] Creation timestamp inRFC3339 text + format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + + This field is a member of `oneof`_ ``_description``. + id (int): + Output only. [Output Only] The unique identifier for the + resource. This identifier is defined by the server. + + This field is a member of `oneof`_ ``_id``. + kind (str): + Output only. [Output Only] Type of the resource. Always + compute#rolloutPlan for rolloutPlans. + + This field is a member of `oneof`_ ``_kind``. + location_scope (str): + The location scope of the rollout plan. If + not specified, the location scope is considered + as ZONAL. Check the LocationScope enum for the + list of possible values. + + This field is a member of `oneof`_ ``_location_scope``. + name (str): + Name of the resource. Provided by the client when the + resource is created. The name must be 1-63 characters long, + and comply withRFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + + This field is a member of `oneof`_ ``_name``. + self_link (str): + Output only. [Output Only] Server-defined fully-qualified + URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + Output only. [Output Only] Server-defined URL for this + resource's resource id. + + This field is a member of `oneof`_ ``_self_link_with_id``. + waves (MutableSequence[google.cloud.compute_v1.types.RolloutPlanWave]): + Required. The waves included in this rollout + plan. + """ + + class LocationScope(proto.Enum): + r"""The location scope of the rollout plan. If not specified, the + location scope is considered as ZONAL. + + Values: + UNDEFINED_LOCATION_SCOPE (0): + A value indicating that the enum field is not + set. + LOCATION_SCOPE_UNSPECIFIED (416410498): + Unspecified value. Considered as ZONAL. + REGIONAL (92288543): + Regional scope. + ZONAL (85547428): + Zonal scope. + """ + + UNDEFINED_LOCATION_SCOPE = 0 + LOCATION_SCOPE_UNSPECIFIED = 416410498 + REGIONAL = 92288543 + ZONAL = 85547428 + + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + id: int = proto.Field( + proto.UINT64, + number=3355, + optional=True, + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + location_scope: str = proto.Field( + proto.STRING, + number=138667338, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + self_link_with_id: str = proto.Field( + proto.STRING, + number=44520962, + optional=True, + ) + waves: MutableSequence["RolloutPlanWave"] = proto.RepeatedField( + proto.MESSAGE, + number=112905370, + message="RolloutPlanWave", + ) + + +class RolloutPlanWave(proto.Message): + r"""A single wave in a rollout plan. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + Optional. The display name of this wave of + the rollout plan. + + This field is a member of `oneof`_ ``_display_name``. + number (int): + Output only. The wave number. + + This field is a member of `oneof`_ ``_number``. + orchestration_options (google.cloud.compute_v1.types.RolloutPlanWaveOrchestrationOptions): + Optional. The orchestration options for this + wave. + + This field is a member of `oneof`_ ``_orchestration_options``. + selectors (MutableSequence[google.cloud.compute_v1.types.RolloutPlanWaveSelector]): + Required. The selectors for this wave. There is a logical + AND between each selector defined in a wave, so a resource + must satisfy the criteria of *all* the specified selectors + to be in scope for the wave. + validation (google.cloud.compute_v1.types.RolloutPlanWaveValidation): + Required. The validation to be performed at + the end of this wave. + + This field is a member of `oneof`_ ``_validation``. + """ + + display_name: str = proto.Field( + proto.STRING, + number=4473832, + optional=True, + ) + number: int = proto.Field( + proto.INT64, + number=39377737, + optional=True, + ) + orchestration_options: "RolloutPlanWaveOrchestrationOptions" = proto.Field( + proto.MESSAGE, + number=93218464, + optional=True, + message="RolloutPlanWaveOrchestrationOptions", + ) + selectors: MutableSequence["RolloutPlanWaveSelector"] = proto.RepeatedField( + proto.MESSAGE, + number=431523956, + message="RolloutPlanWaveSelector", + ) + validation: "RolloutPlanWaveValidation" = proto.Field( + proto.MESSAGE, + number=493308025, + optional=True, + message="RolloutPlanWaveValidation", + ) + + +class RolloutPlanWaveOrchestrationOptions(proto.Message): + r"""Options to control the pace of orchestration of a wave. These + options are required only if the resource being rolled out + follows the Orchestrated pattern. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + delays (MutableSequence[google.cloud.compute_v1.types.RolloutPlanWaveOrchestrationOptionsDelay]): + Optional. Delays, if any, to be added between + batches of projects. We allow multiple Delays to + be specified, letting users set separate delays + between batches of projects corresponding to + different locations and batches of projects + corresponding to the same location. + max_concurrent_locations (int): + Optional. Maximum number of locations to be + orchestrated in parallel. + + This field is a member of `oneof`_ ``_max_concurrent_locations``. + max_concurrent_resources_per_location (int): + Optional. Maximum number of resources to be + orchestrated per location in parallel. + + This field is a member of `oneof`_ ``_max_concurrent_resources_per_location``. + """ + + delays: MutableSequence["RolloutPlanWaveOrchestrationOptionsDelay"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=275150672, + message="RolloutPlanWaveOrchestrationOptionsDelay", + ) + ) + max_concurrent_locations: int = proto.Field( + proto.INT64, + number=493763281, + optional=True, + ) + max_concurrent_resources_per_location: int = proto.Field( + proto.INT64, + number=178401246, + optional=True, + ) + + +class RolloutPlanWaveOrchestrationOptionsDelay(proto.Message): + r"""Options to control the delay, if any, between batches of + projects. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + delimiter (str): + Optional. Controls whether the delay should only be added + between batches of projects corresponding to different + locations, or also between batches of projects corresponding + to the same location. + + Must be set to DELIMITER_UNSPECIFIED if no delay is to be + added. Check the Delimiter enum for the list of possible + values. + + This field is a member of `oneof`_ ``_delimiter``. + duration (str): + Optional. The duration of the delay, if any, + to be added between batches of projects. A zero + duration corresponds to no delay. + + This field is a member of `oneof`_ ``_duration``. + type_ (str): + Optional. Controls whether the specified duration is to be + added at the end of each batch, or if the total processing + time for each batch will be padded if needed to meet the + specified duration. + + Must be set to TYPE_UNSPECIFIED if no delay is to be added. + Check the Type enum for the list of possible values. + + This field is a member of `oneof`_ ``_type``. + """ + + class Delimiter(proto.Enum): + r"""Optional. Controls whether the delay should only be added between + batches of projects corresponding to different locations, or also + between batches of projects corresponding to the same location. + + Must be set to DELIMITER_UNSPECIFIED if no delay is to be added. + + Values: + UNDEFINED_DELIMITER (0): + A value indicating that the enum field is not + set. + DELIMITER_BATCH (253390530): + The delay will also be added between batches + of projects corresponding to the same location. + DELIMITER_LOCATION (189398797): + The delay will only be added between batches + of projects corresponding to different + locations. + DELIMITER_UNSPECIFIED (372199615): + No delay will be added between batches of + projects. Processing will continue with the next + batch as soon as the previous batch of LROs is + done. + """ + + UNDEFINED_DELIMITER = 0 + DELIMITER_BATCH = 253390530 + DELIMITER_LOCATION = 189398797 + DELIMITER_UNSPECIFIED = 372199615 + + class Type(proto.Enum): + r"""Optional. Controls whether the specified duration is to be added at + the end of each batch, or if the total processing time for each + batch will be padded if needed to meet the specified duration. + + Must be set to TYPE_UNSPECIFIED if no delay is to be added. + + Values: + UNDEFINED_TYPE (0): + A value indicating that the enum field is not + set. + TYPE_MINIMUM (234909673): + The total processing time for each batch of + projects will be padded if needed to meet the + specified delay duration. + TYPE_OFFSET (165747000): + The specified delay will directly be added + after each batch of projects as specified by the + delimiter. + TYPE_UNSPECIFIED (437714322): + No delay will be added between batches of + projects. Processing will continue with the next + batch as soon as the previous batch of LROs is + done. + """ + + UNDEFINED_TYPE = 0 + TYPE_MINIMUM = 234909673 + TYPE_OFFSET = 165747000 + TYPE_UNSPECIFIED = 437714322 + + delimiter: str = proto.Field( + proto.STRING, + number=286352903, + optional=True, + ) + duration: str = proto.Field( + proto.STRING, + number=155471252, + optional=True, + ) + type_: str = proto.Field( + proto.STRING, + number=3575610, + optional=True, + ) + + +class RolloutPlanWaveSelector(proto.Message): + r"""A selector which specifies what resource(s) are included in a + given wave. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location_selector (google.cloud.compute_v1.types.RolloutPlanWaveSelectorLocationSelector): + Optional. Roll out to resources by Cloud + locations. + + This field is a member of `oneof`_ ``_location_selector``. + resource_hierarchy_selector (google.cloud.compute_v1.types.RolloutPlanWaveSelectorResourceHierarchySelector): + Optional. Roll out to resources by Cloud + Resource Manager resource hierarchy. + + This field is a member of `oneof`_ ``_resource_hierarchy_selector``. + """ + + location_selector: "RolloutPlanWaveSelectorLocationSelector" = proto.Field( + proto.MESSAGE, + number=422273321, + optional=True, + message="RolloutPlanWaveSelectorLocationSelector", + ) + resource_hierarchy_selector: "RolloutPlanWaveSelectorResourceHierarchySelector" = ( + proto.Field( + proto.MESSAGE, + number=66779770, + optional=True, + message="RolloutPlanWaveSelectorResourceHierarchySelector", + ) + ) + + +class RolloutPlanWaveSelectorLocationSelector(proto.Message): + r"""Roll out to resources by location. + + Attributes: + included_locations (MutableSequence[str]): + Optional. Example: "us-central1-a". + """ + + included_locations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=78239643, + ) + + +class RolloutPlanWaveSelectorResourceHierarchySelector(proto.Message): + r"""Roll out to resources by Cloud Resource Manager resource + hierarchy nodes such as projects, folders, orgs. + + Attributes: + included_folders (MutableSequence[str]): + Optional. Format: "folders/{folder_id}". + included_organizations (MutableSequence[str]): + Optional. Format: "organizations/{organization_id}". + included_projects (MutableSequence[str]): + Optional. Format: "projects/{project_id}". + """ + + included_folders: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=372825410, + ) + included_organizations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=318362461, + ) + included_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=64232605, + ) + + +class RolloutPlanWaveValidation(proto.Message): + r"""The validation to be performed before progressing to the next + wave. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + time_based_validation_metadata (google.cloud.compute_v1.types.RolloutPlanWaveValidationTimeBasedValidationMetadata): + Optional. Metadata required if type = "time". + + This field is a member of `oneof`_ ``_time_based_validation_metadata``. + type_ (str): + Required. The type of the validation. If a + type of validation is associated with a metadata + object, the appropriate metadata field mapping + to the validation type must be provided in the + validation message. Possible values are in + quotes below alongside an explanation: + + "manual": The system waits for an end-user + approval API before progressing to the next + wave. + "time": The system waits for a user specified + duration before progressing to the next + wave. TimeBasedValidation must be provided. + + This field is a member of `oneof`_ ``_type``. + """ + + time_based_validation_metadata: "RolloutPlanWaveValidationTimeBasedValidationMetadata" = proto.Field( + proto.MESSAGE, + number=69499575, + optional=True, + message="RolloutPlanWaveValidationTimeBasedValidationMetadata", + ) + type_: str = proto.Field( + proto.STRING, + number=3575610, + optional=True, + ) + + +class RolloutPlanWaveValidationTimeBasedValidationMetadata(proto.Message): + r"""Metadata required if type = "time". + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + wait_duration (str): + Optional. The duration that the system waits + in between waves. This wait starts after all + changes in the wave are rolled out. + + This field is a member of `oneof`_ ``_wait_duration``. + """ + + wait_duration: str = proto.Field( + proto.STRING, + number=452313374, + optional=True, + ) + + +class RolloutPlansListResponse(proto.Message): + r"""Contains a list of RolloutPlan resources. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + + This field is a member of `oneof`_ ``_etag``. + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1.types.RolloutPlan]): + A list of RolloutPlan resources. + next_page_token (str): + [Output Only] This token allows you to get the next page of + results for list requests. If the number of results is + larger thanmaxResults, use the nextPageToken as a value for + the query parameter pageToken in the next list request. + Subsequent list requests will have their own nextPageToken + to continue paging through the results. + + This field is a member of `oneof`_ ``_next_page_token``. + self_link (str): + Output only. [Output Only] Server-defined URL for this + resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + Output only. [Output Only] Unreachable resources. + end_interface: MixerListResponseWithEtagBuilder + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["RolloutPlan"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="RolloutPlan", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + +class RolloutRolloutEntity(proto.Message): + r"""Specifications of the resource to roll out. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + orchestrated_entity (google.cloud.compute_v1.types.RolloutRolloutEntityOrchestratedEntity): + Optional. Entity details for products using + the Orchestrated Integration model. + + This field is a member of `oneof`_ ``_orchestrated_entity``. + """ + + orchestrated_entity: "RolloutRolloutEntityOrchestratedEntity" = proto.Field( + proto.MESSAGE, + number=409556732, + optional=True, + message="RolloutRolloutEntityOrchestratedEntity", + ) + + +class RolloutRolloutEntityOrchestratedEntity(proto.Message): + r"""This message is used if the resource type follows the + Orchestrated integration model with ProgressiveRollout. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + conflict_behavior (str): + Required. Specifies the behavior of the Rollout if an out of + band update is detected in a project during a Rollout. It + can be one of the following values: + + 1) overwrite : Overwrite the local value with the rollout + value. + 2) no_overwrite : Do not overwrite the local value with the + rollout value. + + This field is a member of `oneof`_ ``_conflict_behavior``. + orchestration_action (str): + Required. Orchestration action during the + Rollout. It can be one of the following values: + + 1) "update": Resources will be updated by the + rollout. 2) "delete": Resources will be deleted + by the rollout. + + This field is a member of `oneof`_ ``_orchestration_action``. + orchestration_source (str): + Required. Fully qualified resource name of + the resource which contains the source of truth + of the configuration being rolled out across + locations/projects. For example, in the case of + a global Rollout which is applied across + regions, this contains the name of the global + resource created by the user which contains a + payload for a resource that is orchestrated + across regions. This follows the following + format: + + //.googleapis.com/projects//locations/global// + e.g. + //osconfig.googleapis.com/projects/1/locations/global/policyOrchestrators/po1 + + This field is a member of `oneof`_ ``_orchestration_source``. + """ + + conflict_behavior: str = proto.Field( + proto.STRING, + number=115729439, + optional=True, + ) + orchestration_action: str = proto.Field( + proto.STRING, + number=109745652, + optional=True, + ) + orchestration_source: str = proto.Field( + proto.STRING, + number=99319769, + optional=True, + ) + + +class RolloutWaveDetails(proto.Message): + r"""Additional metadata about the status of each wave provided by + the server. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + orchestrated_wave_details (google.cloud.compute_v1.types.RolloutWaveDetailsOrchestratedWaveDetails): + Output only. Additional details of the wave + for products using the Orchestrated Integration + model. + + This field is a member of `oneof`_ ``_orchestrated_wave_details``. + wave_display_name (str): + Output only. Wave name. + Ex. wave1 + + This field is a member of `oneof`_ ``_wave_display_name``. + wave_number (int): + Output only. System generated number for the + wave. + + This field is a member of `oneof`_ ``_wave_number``. + """ + + orchestrated_wave_details: "RolloutWaveDetailsOrchestratedWaveDetails" = ( + proto.Field( + proto.MESSAGE, + number=421732181, + optional=True, + message="RolloutWaveDetailsOrchestratedWaveDetails", + ) + ) + wave_display_name: str = proto.Field( + proto.STRING, + number=29521774, + optional=True, + ) + wave_number: int = proto.Field( + proto.INT64, + number=491629391, + optional=True, + ) + + +class RolloutWaveDetailsOrchestratedWaveDetails(proto.Message): + r"""Details of the wave for products using the Orchestrated + integration model. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + completed_resources_count (int): + Output only. Resource completed so far. + + This field is a member of `oneof`_ ``_completed_resources_count``. + estimated_completion_time (str): + Output only. Estimated timestamp at which the + wave will complete. Extrapolated from current + progress. + + This field is a member of `oneof`_ ``_estimated_completion_time``. + estimated_total_resources_count (int): + Output only. Estimated total count of + resources. + + This field is a member of `oneof`_ ``_estimated_total_resources_count``. + failed_locations (MutableSequence[str]): + Output only. Locations that failed during + orchestration, and ProgressiveRollout stopped + retrying. There may be some successful resources + rolled out in the wave as the location may have + failed later in the Rollout. + failed_resources_count (int): + Output only. Resources failed. + + This field is a member of `oneof`_ ``_failed_resources_count``. + location_status (MutableMapping[str, google.cloud.compute_v1.types.RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus]): + Output only. Status of each location in the + wave. Map keys (locations) must be specified + like "us-east1" or "asia-west1-a". + """ + + completed_resources_count: int = proto.Field( + proto.INT64, + number=208328833, + optional=True, + ) + estimated_completion_time: str = proto.Field( + proto.STRING, + number=102305613, + optional=True, + ) + estimated_total_resources_count: int = proto.Field( + proto.INT64, + number=457594807, + optional=True, + ) + failed_locations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=30506460, + ) + failed_resources_count: int = proto.Field( + proto.INT64, + number=391795315, + optional=True, + ) + location_status: MutableMapping[ + str, "RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=19007420, + message="RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus", + ) + + +class RolloutWaveDetailsOrchestratedWaveDetailsLocationStatus(proto.Message): + r"""Represents the status of a location in a wave. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + state (str): + Output only. Location state of the wave. + Check the State enum for the list of possible + values. + + This field is a member of `oneof`_ ``_state``. + """ + + class State(proto.Enum): + r"""Output only. Location state of the wave. + + Values: + UNDEFINED_STATE (0): + A value indicating that the enum field is not + set. + STATE_FAILED (50857931): + Work on the wave failed. + STATE_IN_PROGRESS (413162809): + Work on the wave is in progress. + STATE_PENDING (369985449): + Work on the wave is pending. + STATE_SKIPPED (515663170): + Work on the wave was canceled or skipped. + STATE_SUCCEEDED (466911219): + Work on the wave succeeded. + STATE_UNSPECIFIED (470755401): + Undefined default state. Should never be + exposed to users. + """ + + UNDEFINED_STATE = 0 + STATE_FAILED = 50857931 + STATE_IN_PROGRESS = 413162809 + STATE_PENDING = 369985449 + STATE_SKIPPED = 515663170 + STATE_SUCCEEDED = 466911219 + STATE_UNSPECIFIED = 470755401 + + state: str = proto.Field( + proto.STRING, + number=109757585, + optional=True, + ) + + +class RolloutsListResponse(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + + This field is a member of `oneof`_ ``_etag``. + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1.types.Rollout]): + A list of Rollout resources. + next_page_token (str): + [Output Only] This token allows you to get the next page of + results for list requests. If the number of results is + larger thanmaxResults, use the nextPageToken as a value for + the query parameter pageToken in the next list request. + Subsequent list requests will have their own nextPageToken + to continue paging through the results. + + This field is a member of `oneof`_ ``_next_page_token``. + self_link (str): + Output only. [Output Only] Server-defined URL for this + resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + Output only. [Output Only] Unreachable resources. + end_interface: MixerListResponseWithEtagBuilder + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["Rollout"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="Rollout", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class Route(proto.Message): r"""Represents a Route resource. @@ -131249,9 +134415,106 @@ class SetIamPolicyInstanceRequest(proto.Message): ) -class SetIamPolicyInstanceTemplateRequest(proto.Message): - r"""A request message for InstanceTemplates.SetIamPolicy. See the - method description for details. +class SetIamPolicyInstanceTemplateRequest(proto.Message): + r"""A request message for InstanceTemplates.SetIamPolicy. See the + method description for details. + + Attributes: + global_set_policy_request_resource (google.cloud.compute_v1.types.GlobalSetPolicyRequest): + The body resource for this request + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + """ + + global_set_policy_request_resource: "GlobalSetPolicyRequest" = proto.Field( + proto.MESSAGE, + number=337048498, + message="GlobalSetPolicyRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class SetIamPolicyInstantSnapshotGroupRequest(proto.Message): + r"""A request message for InstantSnapshotGroups.SetIamPolicy. See + the method description for details. + + Attributes: + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + zone (str): + The name of the zone for this request. + zone_set_policy_request_resource (google.cloud.compute_v1.types.ZoneSetPolicyRequest): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + zone_set_policy_request_resource: "ZoneSetPolicyRequest" = proto.Field( + proto.MESSAGE, + number=382082107, + message="ZoneSetPolicyRequest", + ) + + +class SetIamPolicyInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.SetIamPolicy. See the + method description for details. + + Attributes: + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + zone (str): + The name of the zone for this request. + zone_set_policy_request_resource (google.cloud.compute_v1.types.ZoneSetPolicyRequest): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + zone_set_policy_request_resource: "ZoneSetPolicyRequest" = proto.Field( + proto.MESSAGE, + number=382082107, + message="ZoneSetPolicyRequest", + ) + + +class SetIamPolicyInterconnectAttachmentGroupRequest(proto.Message): + r"""A request message for + InterconnectAttachmentGroups.SetIamPolicy. See the method + description for details. Attributes: global_set_policy_request_resource (google.cloud.compute_v1.types.GlobalSetPolicyRequest): @@ -131277,79 +134540,10 @@ class SetIamPolicyInstanceTemplateRequest(proto.Message): ) -class SetIamPolicyInstantSnapshotGroupRequest(proto.Message): - r"""A request message for InstantSnapshotGroups.SetIamPolicy. See +class SetIamPolicyInterconnectGroupRequest(proto.Message): + r"""A request message for InterconnectGroups.SetIamPolicy. See the method description for details. - Attributes: - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - zone (str): - The name of the zone for this request. - zone_set_policy_request_resource (google.cloud.compute_v1.types.ZoneSetPolicyRequest): - The body resource for this request - """ - - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) - zone_set_policy_request_resource: "ZoneSetPolicyRequest" = proto.Field( - proto.MESSAGE, - number=382082107, - message="ZoneSetPolicyRequest", - ) - - -class SetIamPolicyInstantSnapshotRequest(proto.Message): - r"""A request message for InstantSnapshots.SetIamPolicy. See the - method description for details. - - Attributes: - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - zone (str): - The name of the zone for this request. - zone_set_policy_request_resource (google.cloud.compute_v1.types.ZoneSetPolicyRequest): - The body resource for this request - """ - - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) - zone_set_policy_request_resource: "ZoneSetPolicyRequest" = proto.Field( - proto.MESSAGE, - number=382082107, - message="ZoneSetPolicyRequest", - ) - - -class SetIamPolicyInterconnectAttachmentGroupRequest(proto.Message): - r"""A request message for - InterconnectAttachmentGroups.SetIamPolicy. See the method - description for details. - Attributes: global_set_policy_request_resource (google.cloud.compute_v1.types.GlobalSetPolicyRequest): The body resource for this request @@ -131374,9 +134568,9 @@ class SetIamPolicyInterconnectAttachmentGroupRequest(proto.Message): ) -class SetIamPolicyInterconnectGroupRequest(proto.Message): - r"""A request message for InterconnectGroups.SetIamPolicy. See - the method description for details. +class SetIamPolicyLicenseCodeRequest(proto.Message): + r"""A request message for LicenseCodes.SetIamPolicy. See the + method description for details. Attributes: global_set_policy_request_resource (google.cloud.compute_v1.types.GlobalSetPolicyRequest): @@ -136618,7 +139812,7 @@ class SnapshotParams(proto.Message): snapshot. Tag keys and values have the same definition as resource manager tags. Keys and values can be either in numeric format, such as ``tagKeys/{tag_key_id}`` and - ``tagValues/456`` or in namespaced format such as + ``tagValues/{tag_value_id}`` or in namespaced format such as ``{org_id|project_id}/{tag_key_short_name}`` and ``{tag_value_short_name}``. The field is ignored (both PUT & PATCH) when empty. @@ -137940,6 +141134,23 @@ class SslPolicy(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + post_quantum_key_exchange (str): + One of DEFAULT, ENABLED, orDEFERRED. Controls + whether the load balancer negotiates + X25519MLKEM768 key exchange when clients + advertise support for it. When set to DEFAULT, + or if no SSL Policy is attached to the target + proxy, the load balancer disallows + X25519MLKEM768 key exchange before October 2026, + and allows it afterward. When set to ENABLED, + the load balancer allows X25519MLKEM768 key + exchange. When set toDEFERRED, the load balancer + disallows X25519MLKEM768 key exchange until + October 2027, and allows it afterward. Check the + PostQuantumKeyExchange enum for the list of + possible values. + + This field is a member of `oneof`_ ``_post_quantum_key_exchange``. profile (str): Profile specifies the set of SSL features that can be used by the load balancer when negotiating SSL with clients. This @@ -137994,6 +141205,36 @@ class MinTlsVersion(proto.Enum): TLS_1_2 = 33116736 TLS_1_3 = 33116737 + class PostQuantumKeyExchange(proto.Enum): + r"""One of DEFAULT, ENABLED, orDEFERRED. Controls whether the + load balancer negotiates X25519MLKEM768 key exchange when + clients advertise support for it. When set to DEFAULT, or if no + SSL Policy is attached to the target proxy, the load balancer + disallows X25519MLKEM768 key exchange before October 2026, and + allows it afterward. When set to ENABLED, the load balancer + allows X25519MLKEM768 key exchange. When set toDEFERRED, the + load balancer disallows X25519MLKEM768 key exchange until + October 2027, and allows it afterward. + + Values: + UNDEFINED_POST_QUANTUM_KEY_EXCHANGE (0): + A value indicating that the enum field is not + set. + DEFAULT (115302945): + Default behavior: disabled until October + 2026, enabled afterward. + DEFERRED (356775903): + Disabled until October 2027, enabled + afterward. + ENABLED (182130465): + Enabled now. + """ + + UNDEFINED_POST_QUANTUM_KEY_EXCHANGE = 0 + DEFAULT = 115302945 + DEFERRED = 356775903 + ENABLED = 182130465 + class Profile(proto.Enum): r"""Profile specifies the set of SSL features that can be used by the load balancer when negotiating SSL with clients. This can be one @@ -138079,6 +141320,11 @@ class Profile(proto.Enum): number=3373707, optional=True, ) + post_quantum_key_exchange: str = proto.Field( + proto.STRING, + number=245546214, + optional=True, + ) profile: str = proto.Field( proto.STRING, number=227445161, @@ -139931,7 +143177,7 @@ class StoragePoolParams(proto.Message): pool. Tag keys and values have the same definition as resource manager tags. Keys and values can be either in numeric format, such as ``tagKeys/{tag_key_id}`` and - ``tagValues/456`` or in namespaced format such as + ``tagValues/{tag_value_id}`` or in namespaced format such as ``{org_id|project_id}/{tag_key_short_name}`` and ``{tag_value_short_name}``. The field is ignored (both PUT & PATCH) when empty. @@ -148403,6 +151649,65 @@ class UpdateFutureReservationRequest(proto.Message): ) +class UpdateGlobalVmExtensionPolicyRequest(proto.Message): + r"""A request message for GlobalVmExtensionPolicies.Update. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + global_vm_extension_policy (str): + Name of the global VM extension policy to + update. + global_vm_extension_policy_resource (google.cloud.compute_v1.types.GlobalVmExtensionPolicy): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + global_vm_extension_policy: str = proto.Field( + proto.STRING, + number=8334110, + ) + global_vm_extension_policy_resource: "GlobalVmExtensionPolicy" = proto.Field( + proto.MESSAGE, + number=101542927, + message="GlobalVmExtensionPolicy", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + class UpdateHealthCheckRequest(proto.Message): r"""A request message for HealthChecks.Update. See the method description for details. @@ -151768,6 +155073,35 @@ def raw_page(self): ) +class VmExtensionPoliciesScopedList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + vm_extension_policies (MutableSequence[google.cloud.compute_v1.types.VmExtensionPolicy]): + List of VmExtensionPolicy resources contained + in this scope. + warning (google.cloud.compute_v1.types.Warning): + Informational warning which replaces the list + of backend services when the list is empty. + + This field is a member of `oneof`_ ``_warning``. + """ + + vm_extension_policies: MutableSequence["VmExtensionPolicy"] = proto.RepeatedField( + proto.MESSAGE, + number=238490584, + message="VmExtensionPolicy", + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class VmExtensionPolicy(proto.Message): r"""Represents a VM extension policy. @@ -151960,6 +155294,98 @@ class State(proto.Enum): ) +class VmExtensionPolicyAggregatedListResponse(proto.Message): + r"""Response for the aggregated list of VM extension policies. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + + This field is a member of `oneof`_ ``_etag``. + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableMapping[str, google.cloud.compute_v1.types.VmExtensionPoliciesScopedList]): + A list of VmExtensionPoliciesScopedList + resources. + kind (str): + Output only. [Output Only] Type of resource. + Alwayscompute#VmExtensionPolicyAggregatedList for lists of + VmExtensionPolicies. + + This field is a member of `oneof`_ ``_kind``. + next_page_token (str): + [Output Only] This token allows you to get the next page of + results for list requests. If the number of results is + larger thanmaxResults, use the nextPageToken as a value for + the query parameter pageToken in the next list request. + Subsequent list requests will have their own nextPageToken + to continue paging through the results. + + This field is a member of `oneof`_ ``_next_page_token``. + self_link (str): + Output only. [Output Only] Server-defined URL for this + resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + Output only. [Output Only] Unreachable resources. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableMapping[str, "VmExtensionPoliciesScopedList"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=100526016, + message="VmExtensionPoliciesScopedList", + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class VmExtensionPolicyExtensionPolicy(proto.Message): r"""Configuration for a specific VM extension. diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_aggregated_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_aggregated_list_sync.py new file mode 100644 index 000000000000..5b26508f9fd6 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_aggregated_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AggregatedList +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_GlobalVmExtensionPolicies_AggregatedList_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_aggregated_list(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.AggregatedListGlobalVmExtensionPoliciesRequest( + project="project_value", + ) + + # Make the request + page_result = client.aggregated_list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1_generated_GlobalVmExtensionPolicies_AggregatedList_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_delete_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_delete_sync.py new file mode 100644 index 000000000000..ae99a9be5ea6 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Delete +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_GlobalVmExtensionPolicies_Delete_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_delete(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.DeleteGlobalVmExtensionPolicyRequest( + global_vm_extension_policy="global_vm_extension_policy_value", + project="project_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_GlobalVmExtensionPolicies_Delete_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_get_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_get_sync.py new file mode 100644 index 000000000000..8b79b5b18c8e --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Get +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_GlobalVmExtensionPolicies_Get_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.GetGlobalVmExtensionPolicyRequest( + global_vm_extension_policy="global_vm_extension_policy_value", + project="project_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_GlobalVmExtensionPolicies_Get_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_insert_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_insert_sync.py new file mode 100644 index 000000000000..cf6e741e6916 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_insert_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Insert +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_GlobalVmExtensionPolicies_Insert_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_insert(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.InsertGlobalVmExtensionPolicyRequest( + project="project_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_GlobalVmExtensionPolicies_Insert_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_list_sync.py new file mode 100644 index 000000000000..c19ed1f3eb41 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for List +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_GlobalVmExtensionPolicies_List_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_list(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.ListGlobalVmExtensionPoliciesRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1_generated_GlobalVmExtensionPolicies_List_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_update_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_update_sync.py new file mode 100644 index 000000000000..682272394cff --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_global_vm_extension_policies_update_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Update +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_GlobalVmExtensionPolicies_Update_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_update(): + # Create a client + client = compute_v1.GlobalVmExtensionPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.UpdateGlobalVmExtensionPolicyRequest( + global_vm_extension_policy="global_vm_extension_policy_value", + project="project_value", + ) + + # Make the request + response = client.update(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_GlobalVmExtensionPolicies_Update_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_license_codes_get_iam_policy_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_license_codes_get_iam_policy_sync.py new file mode 100644 index 000000000000..7c130af0a600 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_license_codes_get_iam_policy_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_LicenseCodes_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get_iam_policy(): + # Create a client + client = compute_v1.LicenseCodesClient() + + # Initialize request argument(s) + request = compute_v1.GetIamPolicyLicenseCodeRequest( + project="project_value", + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_LicenseCodes_GetIamPolicy_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_license_codes_set_iam_policy_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_license_codes_set_iam_policy_sync.py new file mode 100644 index 000000000000..ff57054fa86e --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_license_codes_set_iam_policy_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_LicenseCodes_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_set_iam_policy(): + # Create a client + client = compute_v1.LicenseCodesClient() + + # Initialize request argument(s) + request = compute_v1.SetIamPolicyLicenseCodeRequest( + project="project_value", + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_LicenseCodes_SetIamPolicy_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_networks_cancel_request_remove_peering_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_networks_cancel_request_remove_peering_sync.py new file mode 100644 index 000000000000..90a87ad5875c --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_networks_cancel_request_remove_peering_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CancelRequestRemovePeering +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Networks_CancelRequestRemovePeering_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_cancel_request_remove_peering(): + # Create a client + client = compute_v1.NetworksClient() + + # Initialize request argument(s) + request = compute_v1.CancelRequestRemovePeeringNetworkRequest( + network="network_value", + project="project_value", + ) + + # Make the request + response = client.cancel_request_remove_peering(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Networks_CancelRequestRemovePeering_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_delete_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_delete_sync.py new file mode 100644 index 000000000000..cde54b4d4032 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Delete +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RolloutPlans_Delete_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_delete(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRolloutPlanRequest( + project="project_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_RolloutPlans_Delete_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_get_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_get_sync.py new file mode 100644 index 000000000000..143addc0fe99 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Get +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RolloutPlans_Get_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.GetRolloutPlanRequest( + project="project_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_RolloutPlans_Get_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_insert_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_insert_sync.py new file mode 100644 index 000000000000..a941744f361f --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_insert_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Insert +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RolloutPlans_Insert_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_insert(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.InsertRolloutPlanRequest( + project="project_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_RolloutPlans_Insert_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_list_sync.py new file mode 100644 index 000000000000..34fa658f74a1 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollout_plans_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for List +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RolloutPlans_List_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_list(): + # Create a client + client = compute_v1.RolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1.ListRolloutPlansRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1_generated_RolloutPlans_List_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_cancel_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_cancel_sync.py new file mode 100644 index 000000000000..9c8e8acce512 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_cancel_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Cancel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Rollouts_Cancel_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_cancel(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.CancelRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.cancel(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Rollouts_Cancel_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_delete_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_delete_sync.py new file mode 100644 index 000000000000..2d01701e524a --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Delete +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Rollouts_Delete_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_delete(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Rollouts_Delete_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_get_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_get_sync.py new file mode 100644 index 000000000000..d8e022f47da9 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Get +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Rollouts_Get_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.GetRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Rollouts_Get_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_list_sync.py new file mode 100644 index 000000000000..f0df11a7fd4f --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for List +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Rollouts_List_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_list(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.ListRolloutsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1_generated_Rollouts_List_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json index 18a681316182..e26c0b33355f 100644 --- a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json +++ b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json @@ -13591,22 +13591,22 @@ "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.HealthChecksClient", - "shortName": "HealthChecksClient" + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient", + "shortName": "GlobalVmExtensionPoliciesClient" }, - "fullName": "google.cloud.compute_v1.HealthChecksClient.aggregated_list", + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.HealthChecks.AggregatedList", + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.HealthChecks", - "shortName": "HealthChecks" + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "shortName": "GlobalVmExtensionPolicies" }, "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListHealthChecksRequest" + "type": "google.cloud.compute_v1.types.AggregatedListGlobalVmExtensionPoliciesRequest" }, { "name": "project", @@ -13625,14 +13625,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.health_checks.pagers.AggregatedListPager", + "resultType": "google.cloud.compute_v1.services.global_vm_extension_policies.pagers.AggregatedListPager", "shortName": "aggregated_list" }, "description": "Sample for AggregatedList", - "file": "compute_v1_generated_health_checks_aggregated_list_sync.py", + "file": "compute_v1_generated_global_vm_extension_policies_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_HealthChecks_AggregatedList_sync", + "regionTag": "compute_v1_generated_GlobalVmExtensionPolicies_AggregatedList_sync", "segments": [ { "end": 52, @@ -13665,37 +13665,41 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_health_checks_aggregated_list_sync.py" + "title": "compute_v1_generated_global_vm_extension_policies_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.HealthChecksClient", - "shortName": "HealthChecksClient" + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient", + "shortName": "GlobalVmExtensionPoliciesClient" }, - "fullName": "google.cloud.compute_v1.HealthChecksClient.delete", + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.HealthChecks.Delete", + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies.Delete", "service": { - "fullName": "google.cloud.compute.v1.HealthChecks", - "shortName": "HealthChecks" + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "shortName": "GlobalVmExtensionPolicies" }, "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteHealthCheckRequest" + "type": "google.cloud.compute_v1.types.DeleteGlobalVmExtensionPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "health_check", + "name": "global_vm_extension_policy", "type": "str" }, + { + "name": "global_vm_extension_policy_rollout_operation_rollout_input_resource", + "type": "google.cloud.compute_v1.types.GlobalVmExtensionPolicyRolloutOperationRolloutInput" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13713,10 +13717,10 @@ "shortName": "delete" }, "description": "Sample for Delete", - "file": "compute_v1_generated_health_checks_delete_sync.py", + "file": "compute_v1_generated_global_vm_extension_policies_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_HealthChecks_Delete_sync", + "regionTag": "compute_v1_generated_GlobalVmExtensionPolicies_Delete_sync", "segments": [ { "end": 52, @@ -13749,35 +13753,35 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_health_checks_delete_sync.py" + "title": "compute_v1_generated_global_vm_extension_policies_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.HealthChecksClient", - "shortName": "HealthChecksClient" + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient", + "shortName": "GlobalVmExtensionPoliciesClient" }, - "fullName": "google.cloud.compute_v1.HealthChecksClient.get", + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.get", "method": { - "fullName": "google.cloud.compute.v1.HealthChecks.Get", + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies.Get", "service": { - "fullName": "google.cloud.compute.v1.HealthChecks", - "shortName": "HealthChecks" + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "shortName": "GlobalVmExtensionPolicies" }, "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetHealthCheckRequest" + "type": "google.cloud.compute_v1.types.GetGlobalVmExtensionPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "health_check", + "name": "global_vm_extension_policy", "type": "str" }, { @@ -13793,14 +13797,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.HealthCheck", + "resultType": "google.cloud.compute_v1.types.GlobalVmExtensionPolicy", "shortName": "get" }, "description": "Sample for Get", - "file": "compute_v1_generated_health_checks_get_sync.py", + "file": "compute_v1_generated_global_vm_extension_policies_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_HealthChecks_Get_sync", + "regionTag": "compute_v1_generated_GlobalVmExtensionPolicies_Get_sync", "segments": [ { "end": 52, @@ -13833,36 +13837,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_health_checks_get_sync.py" + "title": "compute_v1_generated_global_vm_extension_policies_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.HealthChecksClient", - "shortName": "HealthChecksClient" + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient", + "shortName": "GlobalVmExtensionPoliciesClient" }, - "fullName": "google.cloud.compute_v1.HealthChecksClient.insert", + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.HealthChecks.Insert", + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies.Insert", "service": { - "fullName": "google.cloud.compute.v1.HealthChecks", - "shortName": "HealthChecks" + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "shortName": "GlobalVmExtensionPolicies" }, "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertHealthCheckRequest" + "type": "google.cloud.compute_v1.types.InsertGlobalVmExtensionPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "health_check_resource", - "type": "google.cloud.compute_v1.types.HealthCheck" + "name": "global_vm_extension_policy_resource", + "type": "google.cloud.compute_v1.types.GlobalVmExtensionPolicy" }, { "name": "retry", @@ -13881,10 +13885,10 @@ "shortName": "insert" }, "description": "Sample for Insert", - "file": "compute_v1_generated_health_checks_insert_sync.py", + "file": "compute_v1_generated_global_vm_extension_policies_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_HealthChecks_Insert_sync", + "regionTag": "compute_v1_generated_GlobalVmExtensionPolicies_Insert_sync", "segments": [ { "end": 51, @@ -13917,28 +13921,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_health_checks_insert_sync.py" + "title": "compute_v1_generated_global_vm_extension_policies_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.HealthChecksClient", - "shortName": "HealthChecksClient" + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient", + "shortName": "GlobalVmExtensionPoliciesClient" }, - "fullName": "google.cloud.compute_v1.HealthChecksClient.list", + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.list", "method": { - "fullName": "google.cloud.compute.v1.HealthChecks.List", + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies.List", "service": { - "fullName": "google.cloud.compute.v1.HealthChecks", - "shortName": "HealthChecks" + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "shortName": "GlobalVmExtensionPolicies" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListHealthChecksRequest" + "type": "google.cloud.compute_v1.types.ListGlobalVmExtensionPoliciesRequest" }, { "name": "project", @@ -13957,14 +13961,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.health_checks.pagers.ListPager", + "resultType": "google.cloud.compute_v1.services.global_vm_extension_policies.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1_generated_health_checks_list_sync.py", + "file": "compute_v1_generated_global_vm_extension_policies_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_HealthChecks_List_sync", + "regionTag": "compute_v1_generated_GlobalVmExtensionPolicies_List_sync", "segments": [ { "end": 52, @@ -13997,7 +14001,95 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_health_checks_list_sync.py" + "title": "compute_v1_generated_global_vm_extension_policies_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient", + "shortName": "GlobalVmExtensionPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.GlobalVmExtensionPoliciesClient.update", + "method": { + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies.Update", + "service": { + "fullName": "google.cloud.compute.v1.GlobalVmExtensionPolicies", + "shortName": "GlobalVmExtensionPolicies" + }, + "shortName": "Update" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.UpdateGlobalVmExtensionPolicyRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "global_vm_extension_policy", + "type": "str" + }, + { + "name": "global_vm_extension_policy_resource", + "type": "google.cloud.compute_v1.types.GlobalVmExtensionPolicy" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update" + }, + "description": "Sample for Update", + "file": "compute_v1_generated_global_vm_extension_policies_update_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_GlobalVmExtensionPolicies_Update_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_global_vm_extension_policies_update_sync.py" }, { "canonical": true, @@ -14006,31 +14098,107 @@ "fullName": "google.cloud.compute_v1.HealthChecksClient", "shortName": "HealthChecksClient" }, - "fullName": "google.cloud.compute_v1.HealthChecksClient.patch", + "fullName": "google.cloud.compute_v1.HealthChecksClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.HealthChecks.Patch", + "fullName": "google.cloud.compute.v1.HealthChecks.AggregatedList", "service": { "fullName": "google.cloud.compute.v1.HealthChecks", "shortName": "HealthChecks" }, - "shortName": "Patch" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchHealthCheckRequest" + "type": "google.cloud.compute_v1.types.AggregatedListHealthChecksRequest" }, { "name": "project", "type": "str" }, { - "name": "health_check", + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.services.health_checks.pagers.AggregatedListPager", + "shortName": "aggregated_list" + }, + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_health_checks_aggregated_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_HealthChecks_AggregatedList_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_health_checks_aggregated_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.HealthChecksClient", + "shortName": "HealthChecksClient" + }, + "fullName": "google.cloud.compute_v1.HealthChecksClient.delete", + "method": { + "fullName": "google.cloud.compute.v1.HealthChecks.Delete", + "service": { + "fullName": "google.cloud.compute.v1.HealthChecks", + "shortName": "HealthChecks" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.DeleteHealthCheckRequest" + }, + { + "name": "project", "type": "str" }, { - "name": "health_check_resource", - "type": "google.cloud.compute_v1.types.HealthCheck" + "name": "health_check", + "type": "str" }, { "name": "retry", @@ -14046,13 +14214,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "delete" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_health_checks_patch_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_health_checks_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_HealthChecks_Patch_sync", + "regionTag": "compute_v1_generated_HealthChecks_Delete_sync", "segments": [ { "end": 52, @@ -14085,7 +14253,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_health_checks_patch_sync.py" + "title": "compute_v1_generated_health_checks_delete_sync.py" }, { "canonical": true, @@ -14094,32 +14262,28 @@ "fullName": "google.cloud.compute_v1.HealthChecksClient", "shortName": "HealthChecksClient" }, - "fullName": "google.cloud.compute_v1.HealthChecksClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.HealthChecksClient.get", "method": { - "fullName": "google.cloud.compute.v1.HealthChecks.TestIamPermissions", + "fullName": "google.cloud.compute.v1.HealthChecks.Get", "service": { "fullName": "google.cloud.compute.v1.HealthChecks", "shortName": "HealthChecks" }, - "shortName": "TestIamPermissions" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsHealthCheckRequest" + "type": "google.cloud.compute_v1.types.GetHealthCheckRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", + "name": "health_check", "type": "str" }, - { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14133,14 +14297,354 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.cloud.compute_v1.types.HealthCheck", + "shortName": "get" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_health_checks_test_iam_permissions_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_health_checks_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_HealthChecks_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_HealthChecks_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_health_checks_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.HealthChecksClient", + "shortName": "HealthChecksClient" + }, + "fullName": "google.cloud.compute_v1.HealthChecksClient.insert", + "method": { + "fullName": "google.cloud.compute.v1.HealthChecks.Insert", + "service": { + "fullName": "google.cloud.compute.v1.HealthChecks", + "shortName": "HealthChecks" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.InsertHealthCheckRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "health_check_resource", + "type": "google.cloud.compute_v1.types.HealthCheck" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" + }, + "description": "Sample for Insert", + "file": "compute_v1_generated_health_checks_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_HealthChecks_Insert_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_health_checks_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.HealthChecksClient", + "shortName": "HealthChecksClient" + }, + "fullName": "google.cloud.compute_v1.HealthChecksClient.list", + "method": { + "fullName": "google.cloud.compute.v1.HealthChecks.List", + "service": { + "fullName": "google.cloud.compute.v1.HealthChecks", + "shortName": "HealthChecks" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListHealthChecksRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.services.health_checks.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1_generated_health_checks_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_HealthChecks_List_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_health_checks_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.HealthChecksClient", + "shortName": "HealthChecksClient" + }, + "fullName": "google.cloud.compute_v1.HealthChecksClient.patch", + "method": { + "fullName": "google.cloud.compute.v1.HealthChecks.Patch", + "service": { + "fullName": "google.cloud.compute.v1.HealthChecks", + "shortName": "HealthChecks" + }, + "shortName": "Patch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.PatchHealthCheckRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "health_check", + "type": "str" + }, + { + "name": "health_check_resource", + "type": "google.cloud.compute_v1.types.HealthCheck" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" + }, + "description": "Sample for Patch", + "file": "compute_v1_generated_health_checks_patch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_HealthChecks_Patch_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_health_checks_patch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.HealthChecksClient", + "shortName": "HealthChecksClient" + }, + "fullName": "google.cloud.compute_v1.HealthChecksClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.compute.v1.HealthChecks.TestIamPermissions", + "service": { + "fullName": "google.cloud.compute.v1.HealthChecks", + "shortName": "HealthChecks" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.TestIamPermissionsHealthCheckRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_health_checks_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_HealthChecks_TestIamPermissions_sync", "segments": [ { "end": 52, @@ -28903,6 +29407,90 @@ ], "title": "compute_v1_generated_interconnects_set_labels_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicenseCodesClient", + "shortName": "LicenseCodesClient" + }, + "fullName": "google.cloud.compute_v1.LicenseCodesClient.get_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1.LicenseCodes.GetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1.LicenseCodes", + "shortName": "LicenseCodes" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetIamPolicyLicenseCodeRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_license_codes_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_LicenseCodes_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_license_codes_get_iam_policy_sync.py" + }, { "canonical": true, "clientMethod": { @@ -28987,6 +29575,94 @@ ], "title": "compute_v1_generated_license_codes_get_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicenseCodesClient", + "shortName": "LicenseCodesClient" + }, + "fullName": "google.cloud.compute_v1.LicenseCodesClient.set_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1.LicenseCodes.SetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1.LicenseCodes", + "shortName": "LicenseCodes" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.SetIamPolicyLicenseCodeRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "global_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.GlobalSetPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_license_codes_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_LicenseCodes_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_license_codes_set_iam_policy_sync.py" + }, { "canonical": true, "clientMethod": { @@ -34758,19 +35434,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.delete", + "fullName": "google.cloud.compute_v1.NetworksClient.cancel_request_remove_peering", "method": { - "fullName": "google.cloud.compute.v1.Networks.Delete", + "fullName": "google.cloud.compute.v1.Networks.CancelRequestRemovePeering", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "Delete" + "shortName": "CancelRequestRemovePeering" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNetworkRequest" + "type": "google.cloud.compute_v1.types.CancelRequestRemovePeeringNetworkRequest" }, { "name": "project", @@ -34781,88 +35457,8 @@ "type": "str" }, { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" - }, - "description": "Sample for Delete", - "file": "compute_v1_generated_networks_delete_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_Delete_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "compute_v1_generated_networks_delete_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.compute_v1.NetworksClient", - "shortName": "NetworksClient" - }, - "fullName": "google.cloud.compute_v1.NetworksClient.get_effective_firewalls", - "method": { - "fullName": "google.cloud.compute.v1.Networks.GetEffectiveFirewalls", - "service": { - "fullName": "google.cloud.compute.v1.Networks", - "shortName": "Networks" - }, - "shortName": "GetEffectiveFirewalls" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.compute_v1.types.GetEffectiveFirewallsNetworkRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "network", - "type": "str" + "name": "networks_cancel_request_remove_peering_request_resource", + "type": "google.cloud.compute_v1.types.NetworksCancelRequestRemovePeeringRequest" }, { "name": "retry", @@ -34877,14 +35473,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.NetworksGetEffectiveFirewallsResponse", - "shortName": "get_effective_firewalls" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "cancel_request_remove_peering" }, - "description": "Sample for GetEffectiveFirewalls", - "file": "compute_v1_generated_networks_get_effective_firewalls_sync.py", + "description": "Sample for CancelRequestRemovePeering", + "file": "compute_v1_generated_networks_cancel_request_remove_peering_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_GetEffectiveFirewalls_sync", + "regionTag": "compute_v1_generated_Networks_CancelRequestRemovePeering_sync", "segments": [ { "end": 52, @@ -34917,7 +35513,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_get_effective_firewalls_sync.py" + "title": "compute_v1_generated_networks_cancel_request_remove_peering_sync.py" }, { "canonical": true, @@ -34926,19 +35522,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.get", + "fullName": "google.cloud.compute_v1.NetworksClient.delete", "method": { - "fullName": "google.cloud.compute.v1.Networks.Get", + "fullName": "google.cloud.compute.v1.Networks.Delete", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "Get" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNetworkRequest" + "type": "google.cloud.compute_v1.types.DeleteNetworkRequest" }, { "name": "project", @@ -34961,14 +35557,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.Network", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for Get", - "file": "compute_v1_generated_networks_get_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_networks_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_Get_sync", + "regionTag": "compute_v1_generated_Networks_Delete_sync", "segments": [ { "end": 52, @@ -35001,91 +35597,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_get_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.compute_v1.NetworksClient", - "shortName": "NetworksClient" - }, - "fullName": "google.cloud.compute_v1.NetworksClient.insert", - "method": { - "fullName": "google.cloud.compute.v1.Networks.Insert", - "service": { - "fullName": "google.cloud.compute.v1.Networks", - "shortName": "Networks" - }, - "shortName": "Insert" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.compute_v1.types.InsertNetworkRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "network_resource", - "type": "google.cloud.compute_v1.types.Network" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" - }, - "description": "Sample for Insert", - "file": "compute_v1_generated_networks_insert_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_Insert_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "compute_v1_generated_networks_insert_sync.py" + "title": "compute_v1_generated_networks_delete_sync.py" }, { "canonical": true, @@ -35094,19 +35606,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.list_peering_routes", + "fullName": "google.cloud.compute_v1.NetworksClient.get_effective_firewalls", "method": { - "fullName": "google.cloud.compute.v1.Networks.ListPeeringRoutes", + "fullName": "google.cloud.compute.v1.Networks.GetEffectiveFirewalls", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "ListPeeringRoutes" + "shortName": "GetEffectiveFirewalls" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListPeeringRoutesNetworksRequest" + "type": "google.cloud.compute_v1.types.GetEffectiveFirewallsNetworkRequest" }, { "name": "project", @@ -35129,22 +35641,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.networks.pagers.ListPeeringRoutesPager", - "shortName": "list_peering_routes" + "resultType": "google.cloud.compute_v1.types.NetworksGetEffectiveFirewallsResponse", + "shortName": "get_effective_firewalls" }, - "description": "Sample for ListPeeringRoutes", - "file": "compute_v1_generated_networks_list_peering_routes_sync.py", + "description": "Sample for GetEffectiveFirewalls", + "file": "compute_v1_generated_networks_get_effective_firewalls_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_ListPeeringRoutes_sync", + "regionTag": "compute_v1_generated_Networks_GetEffectiveFirewalls_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -35164,12 +35676,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 53, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_list_peering_routes_sync.py" + "title": "compute_v1_generated_networks_get_effective_firewalls_sync.py" }, { "canonical": true, @@ -35178,24 +35690,28 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.list", + "fullName": "google.cloud.compute_v1.NetworksClient.get", "method": { - "fullName": "google.cloud.compute.v1.Networks.List", + "fullName": "google.cloud.compute.v1.Networks.Get", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "List" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNetworksRequest" + "type": "google.cloud.compute_v1.types.GetNetworkRequest" }, { "name": "project", "type": "str" }, + { + "name": "network", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35209,14 +35725,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.networks.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.Network", + "shortName": "get" }, - "description": "Sample for List", - "file": "compute_v1_generated_networks_list_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_networks_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_List_sync", + "regionTag": "compute_v1_generated_Networks_Get_sync", "segments": [ { "end": 52, @@ -35234,22 +35750,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_list_sync.py" + "title": "compute_v1_generated_networks_get_sync.py" }, { "canonical": true, @@ -35258,28 +35774,24 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.patch", + "fullName": "google.cloud.compute_v1.NetworksClient.insert", "method": { - "fullName": "google.cloud.compute.v1.Networks.Patch", + "fullName": "google.cloud.compute.v1.Networks.Insert", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "Patch" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchNetworkRequest" + "type": "google.cloud.compute_v1.types.InsertNetworkRequest" }, { "name": "project", "type": "str" }, - { - "name": "network", - "type": "str" - }, { "name": "network_resource", "type": "google.cloud.compute_v1.types.Network" @@ -35298,21 +35810,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "insert" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_networks_patch_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_networks_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_Patch_sync", + "regionTag": "compute_v1_generated_Networks_Insert_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -35322,22 +35834,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_patch_sync.py" + "title": "compute_v1_generated_networks_insert_sync.py" }, { "canonical": true, @@ -35346,19 +35858,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.remove_peering", + "fullName": "google.cloud.compute_v1.NetworksClient.list_peering_routes", "method": { - "fullName": "google.cloud.compute.v1.Networks.RemovePeering", + "fullName": "google.cloud.compute.v1.Networks.ListPeeringRoutes", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "RemovePeering" + "shortName": "ListPeeringRoutes" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.RemovePeeringNetworkRequest" + "type": "google.cloud.compute_v1.types.ListPeeringRoutesNetworksRequest" }, { "name": "project", @@ -35368,10 +35880,6 @@ "name": "network", "type": "str" }, - { - "name": "networks_remove_peering_request_resource", - "type": "google.cloud.compute_v1.types.NetworksRemovePeeringRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35385,22 +35893,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "remove_peering" + "resultType": "google.cloud.compute_v1.services.networks.pagers.ListPeeringRoutesPager", + "shortName": "list_peering_routes" }, - "description": "Sample for RemovePeering", - "file": "compute_v1_generated_networks_remove_peering_sync.py", + "description": "Sample for ListPeeringRoutes", + "file": "compute_v1_generated_networks_list_peering_routes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_RemovePeering_sync", + "regionTag": "compute_v1_generated_Networks_ListPeeringRoutes_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -35420,12 +35928,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 54, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_remove_peering_sync.py" + "title": "compute_v1_generated_networks_list_peering_routes_sync.py" }, { "canonical": true, @@ -35434,32 +35942,24 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.request_remove_peering", + "fullName": "google.cloud.compute_v1.NetworksClient.list", "method": { - "fullName": "google.cloud.compute.v1.Networks.RequestRemovePeering", + "fullName": "google.cloud.compute.v1.Networks.List", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "RequestRemovePeering" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.RequestRemovePeeringNetworkRequest" + "type": "google.cloud.compute_v1.types.ListNetworksRequest" }, { "name": "project", "type": "str" }, - { - "name": "network", - "type": "str" - }, - { - "name": "networks_request_remove_peering_request_resource", - "type": "google.cloud.compute_v1.types.NetworksRequestRemovePeeringRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35473,14 +35973,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "request_remove_peering" + "resultType": "google.cloud.compute_v1.services.networks.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for RequestRemovePeering", - "file": "compute_v1_generated_networks_request_remove_peering_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_networks_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_RequestRemovePeering_sync", + "regionTag": "compute_v1_generated_Networks_List_sync", "segments": [ { "end": 52, @@ -35498,22 +35998,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_request_remove_peering_sync.py" + "title": "compute_v1_generated_networks_list_sync.py" }, { "canonical": true, @@ -35522,19 +36022,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.switch_to_custom_mode", + "fullName": "google.cloud.compute_v1.NetworksClient.patch", "method": { - "fullName": "google.cloud.compute.v1.Networks.SwitchToCustomMode", + "fullName": "google.cloud.compute.v1.Networks.Patch", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "SwitchToCustomMode" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SwitchToCustomModeNetworkRequest" + "type": "google.cloud.compute_v1.types.PatchNetworkRequest" }, { "name": "project", @@ -35544,6 +36044,10 @@ "name": "network", "type": "str" }, + { + "name": "network_resource", + "type": "google.cloud.compute_v1.types.Network" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35558,13 +36062,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "switch_to_custom_mode" + "shortName": "patch" }, - "description": "Sample for SwitchToCustomMode", - "file": "compute_v1_generated_networks_switch_to_custom_mode_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_networks_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_SwitchToCustomMode_sync", + "regionTag": "compute_v1_generated_Networks_Patch_sync", "segments": [ { "end": 52, @@ -35597,7 +36101,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_switch_to_custom_mode_sync.py" + "title": "compute_v1_generated_networks_patch_sync.py" }, { "canonical": true, @@ -35606,19 +36110,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.update_peering", + "fullName": "google.cloud.compute_v1.NetworksClient.remove_peering", "method": { - "fullName": "google.cloud.compute.v1.Networks.UpdatePeering", + "fullName": "google.cloud.compute.v1.Networks.RemovePeering", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "UpdatePeering" + "shortName": "RemovePeering" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdatePeeringNetworkRequest" + "type": "google.cloud.compute_v1.types.RemovePeeringNetworkRequest" }, { "name": "project", @@ -35629,8 +36133,8 @@ "type": "str" }, { - "name": "networks_update_peering_request_resource", - "type": "google.cloud.compute_v1.types.NetworksUpdatePeeringRequest" + "name": "networks_remove_peering_request_resource", + "type": "google.cloud.compute_v1.types.NetworksRemovePeeringRequest" }, { "name": "retry", @@ -35646,13 +36150,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update_peering" + "shortName": "remove_peering" }, - "description": "Sample for UpdatePeering", - "file": "compute_v1_generated_networks_update_peering_sync.py", + "description": "Sample for RemovePeering", + "file": "compute_v1_generated_networks_remove_peering_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_UpdatePeering_sync", + "regionTag": "compute_v1_generated_Networks_RemovePeering_sync", "segments": [ { "end": 52, @@ -35685,44 +36189,124 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_update_peering_sync.py" + "title": "compute_v1_generated_networks_remove_peering_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeGroupsClient", - "shortName": "NodeGroupsClient" + "fullName": "google.cloud.compute_v1.NetworksClient", + "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.add_nodes", + "fullName": "google.cloud.compute_v1.NetworksClient.request_remove_peering", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.AddNodes", + "fullName": "google.cloud.compute.v1.Networks.RequestRemovePeering", "service": { - "fullName": "google.cloud.compute.v1.NodeGroups", - "shortName": "NodeGroups" + "fullName": "google.cloud.compute.v1.Networks", + "shortName": "Networks" }, - "shortName": "AddNodes" + "shortName": "RequestRemovePeering" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AddNodesNodeGroupRequest" + "type": "google.cloud.compute_v1.types.RequestRemovePeeringNetworkRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "network", "type": "str" }, { - "name": "node_group", + "name": "networks_request_remove_peering_request_resource", + "type": "google.cloud.compute_v1.types.NetworksRequestRemovePeeringRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "request_remove_peering" + }, + "description": "Sample for RequestRemovePeering", + "file": "compute_v1_generated_networks_request_remove_peering_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Networks_RequestRemovePeering_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_networks_request_remove_peering_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.NetworksClient", + "shortName": "NetworksClient" + }, + "fullName": "google.cloud.compute_v1.NetworksClient.switch_to_custom_mode", + "method": { + "fullName": "google.cloud.compute.v1.Networks.SwitchToCustomMode", + "service": { + "fullName": "google.cloud.compute.v1.Networks", + "shortName": "Networks" + }, + "shortName": "SwitchToCustomMode" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.SwitchToCustomModeNetworkRequest" + }, + { + "name": "project", "type": "str" }, { - "name": "node_groups_add_nodes_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsAddNodesRequest" + "name": "network", + "type": "str" }, { "name": "retry", @@ -35738,21 +36322,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_nodes" + "shortName": "switch_to_custom_mode" }, - "description": "Sample for AddNodes", - "file": "compute_v1_generated_node_groups_add_nodes_sync.py", + "description": "Sample for SwitchToCustomMode", + "file": "compute_v1_generated_networks_switch_to_custom_mode_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_AddNodes_sync", + "regionTag": "compute_v1_generated_Networks_SwitchToCustomMode_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -35762,48 +36346,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_add_nodes_sync.py" + "title": "compute_v1_generated_networks_switch_to_custom_mode_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeGroupsClient", - "shortName": "NodeGroupsClient" + "fullName": "google.cloud.compute_v1.NetworksClient", + "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.aggregated_list", + "fullName": "google.cloud.compute_v1.NetworksClient.update_peering", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.AggregatedList", + "fullName": "google.cloud.compute.v1.Networks.UpdatePeering", "service": { - "fullName": "google.cloud.compute.v1.NodeGroups", - "shortName": "NodeGroups" + "fullName": "google.cloud.compute.v1.Networks", + "shortName": "Networks" }, - "shortName": "AggregatedList" + "shortName": "UpdatePeering" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListNodeGroupsRequest" + "type": "google.cloud.compute_v1.types.UpdatePeeringNetworkRequest" }, { "name": "project", "type": "str" }, + { + "name": "network", + "type": "str" + }, + { + "name": "networks_update_peering_request_resource", + "type": "google.cloud.compute_v1.types.NetworksUpdatePeeringRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35817,14 +36409,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.node_groups.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update_peering" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_node_groups_aggregated_list_sync.py", + "description": "Sample for UpdatePeering", + "file": "compute_v1_generated_networks_update_peering_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_AggregatedList_sync", + "regionTag": "compute_v1_generated_Networks_UpdatePeering_sync", "segments": [ { "end": 52, @@ -35842,22 +36434,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_aggregated_list_sync.py" + "title": "compute_v1_generated_networks_update_peering_sync.py" }, { "canonical": true, @@ -35866,19 +36458,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.delete_nodes", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.add_nodes", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.DeleteNodes", + "fullName": "google.cloud.compute.v1.NodeGroups.AddNodes", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "DeleteNodes" + "shortName": "AddNodes" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNodesNodeGroupRequest" + "type": "google.cloud.compute_v1.types.AddNodesNodeGroupRequest" }, { "name": "project", @@ -35893,8 +36485,8 @@ "type": "str" }, { - "name": "node_groups_delete_nodes_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsDeleteNodesRequest" + "name": "node_groups_add_nodes_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsAddNodesRequest" }, { "name": "retry", @@ -35910,13 +36502,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete_nodes" + "shortName": "add_nodes" }, - "description": "Sample for DeleteNodes", - "file": "compute_v1_generated_node_groups_delete_nodes_sync.py", + "description": "Sample for AddNodes", + "file": "compute_v1_generated_node_groups_add_nodes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_DeleteNodes_sync", + "regionTag": "compute_v1_generated_NodeGroups_AddNodes_sync", "segments": [ { "end": 53, @@ -35949,7 +36541,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_delete_nodes_sync.py" + "title": "compute_v1_generated_node_groups_add_nodes_sync.py" }, { "canonical": true, @@ -35958,32 +36550,24 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.delete", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.Delete", + "fullName": "google.cloud.compute.v1.NodeGroups.AggregatedList", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "Delete" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNodeGroupRequest" + "type": "google.cloud.compute_v1.types.AggregatedListNodeGroupsRequest" }, { "name": "project", "type": "str" }, - { - "name": "zone", - "type": "str" - }, - { - "name": "node_group", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35997,22 +36581,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.services.node_groups.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_node_groups_delete_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_node_groups_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_Delete_sync", + "regionTag": "compute_v1_generated_NodeGroups_AggregatedList_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -36022,22 +36606,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_delete_sync.py" + "title": "compute_v1_generated_node_groups_aggregated_list_sync.py" }, { "canonical": true, @@ -36046,19 +36630,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.delete_nodes", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.GetIamPolicy", + "fullName": "google.cloud.compute.v1.NodeGroups.DeleteNodes", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "GetIamPolicy" + "shortName": "DeleteNodes" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyNodeGroupRequest" + "type": "google.cloud.compute_v1.types.DeleteNodesNodeGroupRequest" }, { "name": "project", @@ -36069,9 +36653,13 @@ "type": "str" }, { - "name": "resource", + "name": "node_group", "type": "str" }, + { + "name": "node_groups_delete_nodes_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsDeleteNodesRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -36085,14 +36673,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete_nodes" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_node_groups_get_iam_policy_sync.py", + "description": "Sample for DeleteNodes", + "file": "compute_v1_generated_node_groups_delete_nodes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_NodeGroups_DeleteNodes_sync", "segments": [ { "end": 53, @@ -36125,7 +36713,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_get_iam_policy_sync.py" + "title": "compute_v1_generated_node_groups_delete_nodes_sync.py" }, { "canonical": true, @@ -36134,19 +36722,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.get", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.Get", + "fullName": "google.cloud.compute.v1.NodeGroups.Delete", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "Get" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNodeGroupRequest" + "type": "google.cloud.compute_v1.types.DeleteNodeGroupRequest" }, { "name": "project", @@ -36173,14 +36761,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.NodeGroup", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for Get", - "file": "compute_v1_generated_node_groups_get_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_node_groups_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_Get_sync", + "regionTag": "compute_v1_generated_NodeGroups_Delete_sync", "segments": [ { "end": 53, @@ -36213,7 +36801,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_get_sync.py" + "title": "compute_v1_generated_node_groups_delete_sync.py" }, { "canonical": true, @@ -36222,19 +36810,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.insert", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.Insert", + "fullName": "google.cloud.compute.v1.NodeGroups.GetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "Insert" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertNodeGroupRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyNodeGroupRequest" }, { "name": "project", @@ -36245,12 +36833,8 @@ "type": "str" }, { - "name": "initial_node_count", - "type": "int" - }, - { - "name": "node_group_resource", - "type": "google.cloud.compute_v1.types.NodeGroup" + "name": "resource", + "type": "str" }, { "name": "retry", @@ -36265,14 +36849,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_node_groups_insert_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_node_groups_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_Insert_sync", + "regionTag": "compute_v1_generated_NodeGroups_GetIamPolicy_sync", "segments": [ { "end": 53, @@ -36305,7 +36889,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_insert_sync.py" + "title": "compute_v1_generated_node_groups_get_iam_policy_sync.py" }, { "canonical": true, @@ -36314,19 +36898,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.list_nodes", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.get", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.ListNodes", + "fullName": "google.cloud.compute.v1.NodeGroups.Get", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "ListNodes" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNodesNodeGroupsRequest" + "type": "google.cloud.compute_v1.types.GetNodeGroupRequest" }, { "name": "project", @@ -36353,22 +36937,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.node_groups.pagers.ListNodesPager", - "shortName": "list_nodes" + "resultType": "google.cloud.compute_v1.types.NodeGroup", + "shortName": "get" }, - "description": "Sample for ListNodes", - "file": "compute_v1_generated_node_groups_list_nodes_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_node_groups_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_ListNodes_sync", + "regionTag": "compute_v1_generated_NodeGroups_Get_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -36388,12 +36972,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_list_nodes_sync.py" + "title": "compute_v1_generated_node_groups_get_sync.py" }, { "canonical": true, @@ -36402,19 +36986,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.list", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.List", + "fullName": "google.cloud.compute.v1.NodeGroups.Insert", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "List" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNodeGroupsRequest" + "type": "google.cloud.compute_v1.types.InsertNodeGroupRequest" }, { "name": "project", @@ -36424,6 +37008,14 @@ "name": "zone", "type": "str" }, + { + "name": "initial_node_count", + "type": "int" + }, + { + "name": "node_group_resource", + "type": "google.cloud.compute_v1.types.NodeGroup" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -36437,14 +37029,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.node_groups.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for List", - "file": "compute_v1_generated_node_groups_list_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_node_groups_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_List_sync", + "regionTag": "compute_v1_generated_NodeGroups_Insert_sync", "segments": [ { "end": 53, @@ -36462,22 +37054,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_list_sync.py" + "title": "compute_v1_generated_node_groups_insert_sync.py" }, { "canonical": true, @@ -36486,19 +37078,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.patch", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.list_nodes", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.Patch", + "fullName": "google.cloud.compute.v1.NodeGroups.ListNodes", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "Patch" + "shortName": "ListNodes" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchNodeGroupRequest" + "type": "google.cloud.compute_v1.types.ListNodesNodeGroupsRequest" }, { "name": "project", @@ -36513,8 +37105,88 @@ "type": "str" }, { - "name": "node_group_resource", - "type": "google.cloud.compute_v1.types.NodeGroup" + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.services.node_groups.pagers.ListNodesPager", + "shortName": "list_nodes" + }, + "description": "Sample for ListNodes", + "file": "compute_v1_generated_node_groups_list_nodes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_NodeGroups_ListNodes_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_node_groups_list_nodes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.NodeGroupsClient", + "shortName": "NodeGroupsClient" + }, + "fullName": "google.cloud.compute_v1.NodeGroupsClient.list", + "method": { + "fullName": "google.cloud.compute.v1.NodeGroups.List", + "service": { + "fullName": "google.cloud.compute.v1.NodeGroups", + "shortName": "NodeGroups" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListNodeGroupsRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" }, { "name": "retry", @@ -36529,14 +37201,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.services.node_groups.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_node_groups_patch_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_node_groups_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_Patch_sync", + "regionTag": "compute_v1_generated_NodeGroups_List_sync", "segments": [ { "end": 53, @@ -36554,22 +37226,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_patch_sync.py" + "title": "compute_v1_generated_node_groups_list_sync.py" }, { "canonical": true, @@ -36578,19 +37250,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.perform_maintenance", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.patch", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.PerformMaintenance", + "fullName": "google.cloud.compute.v1.NodeGroups.Patch", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "PerformMaintenance" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PerformMaintenanceNodeGroupRequest" + "type": "google.cloud.compute_v1.types.PatchNodeGroupRequest" }, { "name": "project", @@ -36605,8 +37277,8 @@ "type": "str" }, { - "name": "node_groups_perform_maintenance_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsPerformMaintenanceRequest" + "name": "node_group_resource", + "type": "google.cloud.compute_v1.types.NodeGroup" }, { "name": "retry", @@ -36622,13 +37294,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "perform_maintenance" + "shortName": "patch" }, - "description": "Sample for PerformMaintenance", - "file": "compute_v1_generated_node_groups_perform_maintenance_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_node_groups_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_PerformMaintenance_sync", + "regionTag": "compute_v1_generated_NodeGroups_Patch_sync", "segments": [ { "end": 53, @@ -36661,7 +37333,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_perform_maintenance_sync.py" + "title": "compute_v1_generated_node_groups_patch_sync.py" }, { "canonical": true, @@ -36670,19 +37342,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.perform_maintenance", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.SetIamPolicy", + "fullName": "google.cloud.compute.v1.NodeGroups.PerformMaintenance", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "SetIamPolicy" + "shortName": "PerformMaintenance" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyNodeGroupRequest" + "type": "google.cloud.compute_v1.types.PerformMaintenanceNodeGroupRequest" }, { "name": "project", @@ -36693,12 +37365,12 @@ "type": "str" }, { - "name": "resource", + "name": "node_group", "type": "str" }, { - "name": "zone_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.ZoneSetPolicyRequest" + "name": "node_groups_perform_maintenance_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsPerformMaintenanceRequest" }, { "name": "retry", @@ -36713,14 +37385,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "perform_maintenance" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_node_groups_set_iam_policy_sync.py", + "description": "Sample for PerformMaintenance", + "file": "compute_v1_generated_node_groups_perform_maintenance_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_NodeGroups_PerformMaintenance_sync", "segments": [ { "end": 53, @@ -36753,7 +37425,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_set_iam_policy_sync.py" + "title": "compute_v1_generated_node_groups_perform_maintenance_sync.py" }, { "canonical": true, @@ -36762,19 +37434,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.set_node_template", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.SetNodeTemplate", + "fullName": "google.cloud.compute.v1.NodeGroups.SetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "SetNodeTemplate" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetNodeTemplateNodeGroupRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyNodeGroupRequest" }, { "name": "project", @@ -36785,12 +37457,12 @@ "type": "str" }, { - "name": "node_group", + "name": "resource", "type": "str" }, { - "name": "node_groups_set_node_template_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsSetNodeTemplateRequest" + "name": "zone_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.ZoneSetPolicyRequest" }, { "name": "retry", @@ -36805,14 +37477,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_node_template" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for SetNodeTemplate", - "file": "compute_v1_generated_node_groups_set_node_template_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_node_groups_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_SetNodeTemplate_sync", + "regionTag": "compute_v1_generated_NodeGroups_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -36845,7 +37517,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_set_node_template_sync.py" + "title": "compute_v1_generated_node_groups_set_iam_policy_sync.py" }, { "canonical": true, @@ -36854,19 +37526,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.simulate_maintenance_event", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.set_node_template", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.SimulateMaintenanceEvent", + "fullName": "google.cloud.compute.v1.NodeGroups.SetNodeTemplate", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "SimulateMaintenanceEvent" + "shortName": "SetNodeTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SimulateMaintenanceEventNodeGroupRequest" + "type": "google.cloud.compute_v1.types.SetNodeTemplateNodeGroupRequest" }, { "name": "project", @@ -36881,8 +37553,8 @@ "type": "str" }, { - "name": "node_groups_simulate_maintenance_event_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsSimulateMaintenanceEventRequest" + "name": "node_groups_set_node_template_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsSetNodeTemplateRequest" }, { "name": "retry", @@ -36898,13 +37570,105 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "simulate_maintenance_event" + "shortName": "set_node_template" }, - "description": "Sample for SimulateMaintenanceEvent", - "file": "compute_v1_generated_node_groups_simulate_maintenance_event_sync.py", + "description": "Sample for SetNodeTemplate", + "file": "compute_v1_generated_node_groups_set_node_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_SimulateMaintenanceEvent_sync", + "regionTag": "compute_v1_generated_NodeGroups_SetNodeTemplate_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_node_groups_set_node_template_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.NodeGroupsClient", + "shortName": "NodeGroupsClient" + }, + "fullName": "google.cloud.compute_v1.NodeGroupsClient.simulate_maintenance_event", + "method": { + "fullName": "google.cloud.compute.v1.NodeGroups.SimulateMaintenanceEvent", + "service": { + "fullName": "google.cloud.compute.v1.NodeGroups", + "shortName": "NodeGroups" + }, + "shortName": "SimulateMaintenanceEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.SimulateMaintenanceEventNodeGroupRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "node_group", + "type": "str" + }, + { + "name": "node_groups_simulate_maintenance_event_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsSimulateMaintenanceEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "simulate_maintenance_event" + }, + "description": "Sample for SimulateMaintenanceEvent", + "file": "compute_v1_generated_node_groups_simulate_maintenance_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_NodeGroups_SimulateMaintenanceEvent_sync", "segments": [ { "end": 53, @@ -65245,41 +66009,753 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_get_iam_policy_sync.py" + "title": "compute_v1_generated_reservations_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationsClient", + "shortName": "ReservationsClient" + }, + "fullName": "google.cloud.compute_v1.ReservationsClient.get", + "method": { + "fullName": "google.cloud.compute.v1.Reservations.Get", + "service": { + "fullName": "google.cloud.compute.v1.Reservations", + "shortName": "Reservations" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetReservationRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "reservation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.Reservation", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1_generated_reservations_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Reservations_Get_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservations_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationsClient", + "shortName": "ReservationsClient" + }, + "fullName": "google.cloud.compute_v1.ReservationsClient.insert", + "method": { + "fullName": "google.cloud.compute.v1.Reservations.Insert", + "service": { + "fullName": "google.cloud.compute.v1.Reservations", + "shortName": "Reservations" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.InsertReservationRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "reservation_resource", + "type": "google.cloud.compute_v1.types.Reservation" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" + }, + "description": "Sample for Insert", + "file": "compute_v1_generated_reservations_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Reservations_Insert_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservations_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationsClient", + "shortName": "ReservationsClient" + }, + "fullName": "google.cloud.compute_v1.ReservationsClient.list", + "method": { + "fullName": "google.cloud.compute.v1.Reservations.List", + "service": { + "fullName": "google.cloud.compute.v1.Reservations", + "shortName": "Reservations" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListReservationsRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.services.reservations.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1_generated_reservations_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Reservations_List_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservations_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationsClient", + "shortName": "ReservationsClient" + }, + "fullName": "google.cloud.compute_v1.ReservationsClient.perform_maintenance", + "method": { + "fullName": "google.cloud.compute.v1.Reservations.PerformMaintenance", + "service": { + "fullName": "google.cloud.compute.v1.Reservations", + "shortName": "Reservations" + }, + "shortName": "PerformMaintenance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.PerformMaintenanceReservationRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "reservation", + "type": "str" + }, + { + "name": "reservations_perform_maintenance_request_resource", + "type": "google.cloud.compute_v1.types.ReservationsPerformMaintenanceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "perform_maintenance" + }, + "description": "Sample for PerformMaintenance", + "file": "compute_v1_generated_reservations_perform_maintenance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Reservations_PerformMaintenance_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservations_perform_maintenance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationsClient", + "shortName": "ReservationsClient" + }, + "fullName": "google.cloud.compute_v1.ReservationsClient.resize", + "method": { + "fullName": "google.cloud.compute.v1.Reservations.Resize", + "service": { + "fullName": "google.cloud.compute.v1.Reservations", + "shortName": "Reservations" + }, + "shortName": "Resize" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ResizeReservationRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "reservation", + "type": "str" + }, + { + "name": "reservations_resize_request_resource", + "type": "google.cloud.compute_v1.types.ReservationsResizeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "resize" + }, + "description": "Sample for Resize", + "file": "compute_v1_generated_reservations_resize_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Reservations_Resize_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservations_resize_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationsClient", + "shortName": "ReservationsClient" + }, + "fullName": "google.cloud.compute_v1.ReservationsClient.set_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1.Reservations.SetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1.Reservations", + "shortName": "Reservations" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.SetIamPolicyReservationRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "zone_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.ZoneSetPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_reservations_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Reservations_SetIamPolicy_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservations_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationsClient", + "shortName": "ReservationsClient" + }, + "fullName": "google.cloud.compute_v1.ReservationsClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.compute.v1.Reservations.TestIamPermissions", + "service": { + "fullName": "google.cloud.compute.v1.Reservations", + "shortName": "Reservations" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.TestIamPermissionsReservationRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_reservations_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Reservations_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservations_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationsClient", + "shortName": "ReservationsClient" + }, + "fullName": "google.cloud.compute_v1.ReservationsClient.update", + "method": { + "fullName": "google.cloud.compute.v1.Reservations.Update", + "service": { + "fullName": "google.cloud.compute.v1.Reservations", + "shortName": "Reservations" + }, + "shortName": "Update" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.UpdateReservationRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "reservation", + "type": "str" + }, + { + "name": "reservation_resource", + "type": "google.cloud.compute_v1.types.Reservation" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update" + }, + "description": "Sample for Update", + "file": "compute_v1_generated_reservations_update_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Reservations_Update_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservations_update_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ReservationsClient", - "shortName": "ReservationsClient" + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", + "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ReservationsClient.get", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.Reservations.Get", + "fullName": "google.cloud.compute.v1.ResourcePolicies.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.Reservations", - "shortName": "Reservations" + "fullName": "google.cloud.compute.v1.ResourcePolicies", + "shortName": "ResourcePolicies" }, - "shortName": "Get" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetReservationRequest" + "type": "google.cloud.compute_v1.types.AggregatedListResourcePoliciesRequest" }, { "name": "project", "type": "str" }, - { - "name": "zone", - "type": "str" - }, - { - "name": "reservation", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -65293,22 +66769,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.Reservation", - "shortName": "get" + "resultType": "google.cloud.compute_v1.services.resource_policies.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Get", - "file": "compute_v1_generated_reservations_get_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_resource_policies_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Reservations_Get_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_AggregatedList_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -65318,55 +66794,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_get_sync.py" + "title": "compute_v1_generated_resource_policies_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ReservationsClient", - "shortName": "ReservationsClient" + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", + "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ReservationsClient.insert", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.Reservations.Insert", + "fullName": "google.cloud.compute.v1.ResourcePolicies.Delete", "service": { - "fullName": "google.cloud.compute.v1.Reservations", - "shortName": "Reservations" + "fullName": "google.cloud.compute.v1.ResourcePolicies", + "shortName": "ResourcePolicies" }, - "shortName": "Insert" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertReservationRequest" + "type": "google.cloud.compute_v1.types.DeleteResourcePolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "reservation_resource", - "type": "google.cloud.compute_v1.types.Reservation" + "name": "resource_policy", + "type": "str" }, { "name": "retry", @@ -65382,21 +66858,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "delete" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_reservations_insert_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_resource_policies_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Reservations_Insert_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_Delete_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -65406,50 +66882,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_insert_sync.py" + "title": "compute_v1_generated_resource_policies_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ReservationsClient", - "shortName": "ReservationsClient" + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", + "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ReservationsClient.list", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.Reservations.List", + "fullName": "google.cloud.compute.v1.ResourcePolicies.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.Reservations", - "shortName": "Reservations" + "fullName": "google.cloud.compute.v1.ResourcePolicies", + "shortName": "ResourcePolicies" }, - "shortName": "List" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListReservationsRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyResourcePolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", + "type": "str" + }, + { + "name": "resource", "type": "str" }, { @@ -65465,14 +66945,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.reservations.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for List", - "file": "compute_v1_generated_reservations_list_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_resource_policies_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Reservations_List_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_GetIamPolicy_sync", "segments": [ { "end": 53, @@ -65490,60 +66970,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_list_sync.py" + "title": "compute_v1_generated_resource_policies_get_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ReservationsClient", - "shortName": "ReservationsClient" + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", + "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ReservationsClient.perform_maintenance", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.get", "method": { - "fullName": "google.cloud.compute.v1.Reservations.PerformMaintenance", + "fullName": "google.cloud.compute.v1.ResourcePolicies.Get", "service": { - "fullName": "google.cloud.compute.v1.Reservations", - "shortName": "Reservations" + "fullName": "google.cloud.compute.v1.ResourcePolicies", + "shortName": "ResourcePolicies" }, - "shortName": "PerformMaintenance" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PerformMaintenanceReservationRequest" + "type": "google.cloud.compute_v1.types.GetResourcePolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "reservation", + "name": "resource_policy", "type": "str" }, - { - "name": "reservations_perform_maintenance_request_resource", - "type": "google.cloud.compute_v1.types.ReservationsPerformMaintenanceRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -65557,14 +67033,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "perform_maintenance" + "resultType": "google.cloud.compute_v1.types.ResourcePolicy", + "shortName": "get" }, - "description": "Sample for PerformMaintenance", - "file": "compute_v1_generated_reservations_perform_maintenance_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_resource_policies_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Reservations_PerformMaintenance_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_Get_sync", "segments": [ { "end": 53, @@ -65597,44 +67073,40 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_perform_maintenance_sync.py" + "title": "compute_v1_generated_resource_policies_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ReservationsClient", - "shortName": "ReservationsClient" + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", + "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ReservationsClient.resize", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.Reservations.Resize", + "fullName": "google.cloud.compute.v1.ResourcePolicies.Insert", "service": { - "fullName": "google.cloud.compute.v1.Reservations", - "shortName": "Reservations" + "fullName": "google.cloud.compute.v1.ResourcePolicies", + "shortName": "ResourcePolicies" }, - "shortName": "Resize" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ResizeReservationRequest" + "type": "google.cloud.compute_v1.types.InsertResourcePolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", - "type": "str" - }, - { - "name": "reservation", + "name": "region", "type": "str" }, { - "name": "reservations_resize_request_resource", - "type": "google.cloud.compute_v1.types.ReservationsResizeRequest" + "name": "resource_policy_resource", + "type": "google.cloud.compute_v1.types.ResourcePolicy" }, { "name": "retry", @@ -65650,21 +67122,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "resize" + "shortName": "insert" }, - "description": "Sample for Resize", - "file": "compute_v1_generated_reservations_resize_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_resource_policies_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Reservations_Resize_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -65674,60 +67146,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_resize_sync.py" + "title": "compute_v1_generated_resource_policies_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ReservationsClient", - "shortName": "ReservationsClient" + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", + "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ReservationsClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.list", "method": { - "fullName": "google.cloud.compute.v1.Reservations.SetIamPolicy", + "fullName": "google.cloud.compute.v1.ResourcePolicies.List", "service": { - "fullName": "google.cloud.compute.v1.Reservations", - "shortName": "Reservations" + "fullName": "google.cloud.compute.v1.ResourcePolicies", + "shortName": "ResourcePolicies" }, - "shortName": "SetIamPolicy" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyReservationRequest" + "type": "google.cloud.compute_v1.types.ListResourcePoliciesRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", - "type": "str" - }, - { - "name": "resource", + "name": "region", "type": "str" }, - { - "name": "zone_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.ZoneSetPolicyRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -65741,14 +67205,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.cloud.compute_v1.services.resource_policies.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_reservations_set_iam_policy_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_resource_policies_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Reservations_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_List_sync", "segments": [ { "end": 53, @@ -65766,59 +67230,59 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_set_iam_policy_sync.py" + "title": "compute_v1_generated_resource_policies_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ReservationsClient", - "shortName": "ReservationsClient" + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", + "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ReservationsClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.patch", "method": { - "fullName": "google.cloud.compute.v1.Reservations.TestIamPermissions", + "fullName": "google.cloud.compute.v1.ResourcePolicies.Patch", "service": { - "fullName": "google.cloud.compute.v1.Reservations", - "shortName": "Reservations" + "fullName": "google.cloud.compute.v1.ResourcePolicies", + "shortName": "ResourcePolicies" }, - "shortName": "TestIamPermissions" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsReservationRequest" + "type": "google.cloud.compute_v1.types.PatchResourcePolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "resource", + "name": "resource_policy", "type": "str" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "resource_policy_resource", + "type": "google.cloud.compute_v1.types.ResourcePolicy" }, { "name": "retry", @@ -65833,14 +67297,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_reservations_test_iam_permissions_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_resource_policies_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Reservations_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_Patch_sync", "segments": [ { "end": 53, @@ -65873,44 +67337,44 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_test_iam_permissions_sync.py" + "title": "compute_v1_generated_resource_policies_patch_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ReservationsClient", - "shortName": "ReservationsClient" + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", + "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ReservationsClient.update", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.Reservations.Update", + "fullName": "google.cloud.compute.v1.ResourcePolicies.SetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.Reservations", - "shortName": "Reservations" + "fullName": "google.cloud.compute.v1.ResourcePolicies", + "shortName": "ResourcePolicies" }, - "shortName": "Update" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdateReservationRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyResourcePolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "reservation", + "name": "resource", "type": "str" }, { - "name": "reservation_resource", - "type": "google.cloud.compute_v1.types.Reservation" + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" }, { "name": "retry", @@ -65925,14 +67389,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for Update", - "file": "compute_v1_generated_reservations_update_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_resource_policies_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Reservations_Update_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -65965,7 +67429,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_reservations_update_sync.py" + "title": "compute_v1_generated_resource_policies_set_iam_policy_sync.py" }, { "canonical": true, @@ -65974,24 +67438,36 @@ "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", "shortName": "ResourcePoliciesClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.aggregated_list", + "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.AggregatedList", + "fullName": "google.cloud.compute.v1.ResourcePolicies.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.ResourcePolicies", "shortName": "ResourcePolicies" }, - "shortName": "AggregatedList" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListResourcePoliciesRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsResourcePolicyRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -66005,22 +67481,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.resource_policies.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_resource_policies_aggregated_list_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_resource_policies_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_AggregatedList_sync", + "regionTag": "compute_v1_generated_ResourcePolicies_TestIamPermissions_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -66030,54 +67506,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_aggregated_list_sync.py" + "title": "compute_v1_generated_resource_policies_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", - "shortName": "ResourcePoliciesClient" + "fullName": "google.cloud.compute_v1.RolloutPlansClient", + "shortName": "RolloutPlansClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.delete", + "fullName": "google.cloud.compute_v1.RolloutPlansClient.delete", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.Delete", + "fullName": "google.cloud.compute.v1.RolloutPlans.Delete", "service": { - "fullName": "google.cloud.compute.v1.ResourcePolicies", - "shortName": "ResourcePolicies" + "fullName": "google.cloud.compute.v1.RolloutPlans", + "shortName": "RolloutPlans" }, "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteResourcePolicyRequest" + "type": "google.cloud.compute_v1.types.DeleteRolloutPlanRequest" }, { "name": "project", "type": "str" }, { - "name": "region", - "type": "str" - }, - { - "name": "resource_policy", + "name": "rollout_plan", "type": "str" }, { @@ -66097,18 +67569,18 @@ "shortName": "delete" }, "description": "Sample for Delete", - "file": "compute_v1_generated_resource_policies_delete_sync.py", + "file": "compute_v1_generated_rollout_plans_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_Delete_sync", + "regionTag": "compute_v1_generated_RolloutPlans_Delete_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -66118,54 +67590,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_delete_sync.py" + "title": "compute_v1_generated_rollout_plans_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", - "shortName": "ResourcePoliciesClient" + "fullName": "google.cloud.compute_v1.RolloutPlansClient", + "shortName": "RolloutPlansClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.RolloutPlansClient.get", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.GetIamPolicy", + "fullName": "google.cloud.compute.v1.RolloutPlans.Get", "service": { - "fullName": "google.cloud.compute.v1.ResourcePolicies", - "shortName": "ResourcePolicies" + "fullName": "google.cloud.compute.v1.RolloutPlans", + "shortName": "RolloutPlans" }, - "shortName": "GetIamPolicy" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyResourcePolicyRequest" + "type": "google.cloud.compute_v1.types.GetRolloutPlanRequest" }, { "name": "project", "type": "str" }, { - "name": "region", - "type": "str" - }, - { - "name": "resource", + "name": "rollout_plan", "type": "str" }, { @@ -66181,22 +67649,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.compute_v1.types.RolloutPlan", + "shortName": "get" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_resource_policies_get_iam_policy_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_rollout_plans_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_RolloutPlans_Get_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -66206,55 +67674,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_get_iam_policy_sync.py" + "title": "compute_v1_generated_rollout_plans_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", - "shortName": "ResourcePoliciesClient" + "fullName": "google.cloud.compute_v1.RolloutPlansClient", + "shortName": "RolloutPlansClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.get", + "fullName": "google.cloud.compute_v1.RolloutPlansClient.insert", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.Get", + "fullName": "google.cloud.compute.v1.RolloutPlans.Insert", "service": { - "fullName": "google.cloud.compute.v1.ResourcePolicies", - "shortName": "ResourcePolicies" + "fullName": "google.cloud.compute.v1.RolloutPlans", + "shortName": "RolloutPlans" }, - "shortName": "Get" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetResourcePolicyRequest" + "type": "google.cloud.compute_v1.types.InsertRolloutPlanRequest" }, { "name": "project", "type": "str" }, { - "name": "region", - "type": "str" - }, - { - "name": "resource_policy", - "type": "str" + "name": "rollout_plan_resource", + "type": "google.cloud.compute_v1.types.RolloutPlan" }, { "name": "retry", @@ -66269,22 +67733,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.ResourcePolicy", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for Get", - "file": "compute_v1_generated_resource_policies_get_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_rollout_plans_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_Get_sync", + "regionTag": "compute_v1_generated_RolloutPlans_Insert_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -66294,56 +67758,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_get_sync.py" + "title": "compute_v1_generated_rollout_plans_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", - "shortName": "ResourcePoliciesClient" + "fullName": "google.cloud.compute_v1.RolloutPlansClient", + "shortName": "RolloutPlansClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.insert", + "fullName": "google.cloud.compute_v1.RolloutPlansClient.list", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.Insert", + "fullName": "google.cloud.compute.v1.RolloutPlans.List", "service": { - "fullName": "google.cloud.compute.v1.ResourcePolicies", - "shortName": "ResourcePolicies" + "fullName": "google.cloud.compute.v1.RolloutPlans", + "shortName": "RolloutPlans" }, - "shortName": "Insert" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertResourcePolicyRequest" + "type": "google.cloud.compute_v1.types.ListRolloutPlansRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, - { - "name": "resource_policy_resource", - "type": "google.cloud.compute_v1.types.ResourcePolicy" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -66357,14 +67813,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.services.rollout_plans.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_resource_policies_insert_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_rollout_plans_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_Insert_sync", + "regionTag": "compute_v1_generated_RolloutPlans_List_sync", "segments": [ { "end": 52, @@ -66382,50 +67838,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_insert_sync.py" + "title": "compute_v1_generated_rollout_plans_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", - "shortName": "ResourcePoliciesClient" + "fullName": "google.cloud.compute_v1.RolloutsClient", + "shortName": "RolloutsClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.list", + "fullName": "google.cloud.compute_v1.RolloutsClient.cancel", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.List", + "fullName": "google.cloud.compute.v1.Rollouts.Cancel", "service": { - "fullName": "google.cloud.compute.v1.ResourcePolicies", - "shortName": "ResourcePolicies" + "fullName": "google.cloud.compute.v1.Rollouts", + "shortName": "Rollouts" }, - "shortName": "List" + "shortName": "Cancel" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListResourcePoliciesRequest" + "type": "google.cloud.compute_v1.types.CancelRolloutRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "rollout", "type": "str" }, { @@ -66441,22 +67897,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.resource_policies.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "cancel" }, - "description": "Sample for List", - "file": "compute_v1_generated_resource_policies_list_sync.py", + "description": "Sample for Cancel", + "file": "compute_v1_generated_rollouts_cancel_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_List_sync", + "regionTag": "compute_v1_generated_Rollouts_Cancel_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -66476,50 +67932,42 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 53, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_list_sync.py" + "title": "compute_v1_generated_rollouts_cancel_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", - "shortName": "ResourcePoliciesClient" + "fullName": "google.cloud.compute_v1.RolloutsClient", + "shortName": "RolloutsClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.patch", + "fullName": "google.cloud.compute_v1.RolloutsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.Patch", + "fullName": "google.cloud.compute.v1.Rollouts.Delete", "service": { - "fullName": "google.cloud.compute.v1.ResourcePolicies", - "shortName": "ResourcePolicies" + "fullName": "google.cloud.compute.v1.Rollouts", + "shortName": "Rollouts" }, - "shortName": "Patch" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchResourcePolicyRequest" + "type": "google.cloud.compute_v1.types.DeleteRolloutRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "rollout", "type": "str" }, - { - "name": "resource_policy", - "type": "str" - }, - { - "name": "resource_policy_resource", - "type": "google.cloud.compute_v1.types.ResourcePolicy" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -66534,21 +67982,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "delete" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_resource_policies_patch_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_rollouts_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_Patch_sync", + "regionTag": "compute_v1_generated_Rollouts_Delete_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -66558,60 +68006,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_patch_sync.py" + "title": "compute_v1_generated_rollouts_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", - "shortName": "ResourcePoliciesClient" + "fullName": "google.cloud.compute_v1.RolloutsClient", + "shortName": "RolloutsClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.RolloutsClient.get", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.SetIamPolicy", + "fullName": "google.cloud.compute.v1.Rollouts.Get", "service": { - "fullName": "google.cloud.compute.v1.ResourcePolicies", - "shortName": "ResourcePolicies" + "fullName": "google.cloud.compute.v1.Rollouts", + "shortName": "Rollouts" }, - "shortName": "SetIamPolicy" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyResourcePolicyRequest" + "type": "google.cloud.compute_v1.types.GetRolloutRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "rollout", "type": "str" }, - { - "name": "resource", - "type": "str" - }, - { - "name": "region_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -66625,22 +68065,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.cloud.compute_v1.types.Rollout", + "shortName": "get" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_resource_policies_set_iam_policy_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_rollouts_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_Rollouts_Get_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -66650,60 +68090,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_set_iam_policy_sync.py" + "title": "compute_v1_generated_rollouts_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient", - "shortName": "ResourcePoliciesClient" + "fullName": "google.cloud.compute_v1.RolloutsClient", + "shortName": "RolloutsClient" }, - "fullName": "google.cloud.compute_v1.ResourcePoliciesClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.RolloutsClient.list", "method": { - "fullName": "google.cloud.compute.v1.ResourcePolicies.TestIamPermissions", + "fullName": "google.cloud.compute.v1.Rollouts.List", "service": { - "fullName": "google.cloud.compute.v1.ResourcePolicies", - "shortName": "ResourcePolicies" + "fullName": "google.cloud.compute.v1.Rollouts", + "shortName": "Rollouts" }, - "shortName": "TestIamPermissions" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsResourcePolicyRequest" + "type": "google.cloud.compute_v1.types.ListRolloutsRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -66717,22 +68145,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.cloud.compute_v1.services.rollouts.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_resource_policies_test_iam_permissions_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_rollouts_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_ResourcePolicies_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_Rollouts_List_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -66742,22 +68170,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_resource_policies_test_iam_permissions_sync.py" + "title": "compute_v1_generated_rollouts_list_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py index 6d9dfee8f5a5..1f53698f8960 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py @@ -4364,6 +4364,7 @@ def test_insert_rest_call_success(request_type): "time_window_sec": 1600, }, "scaling_schedules": {}, + "stabilization_period_sec": 2553, }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", @@ -4769,6 +4770,7 @@ def test_patch_rest_call_success(request_type): "time_window_sec": 1600, }, "scaling_schedules": {}, + "stabilization_period_sec": 2553, }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", @@ -5255,6 +5257,7 @@ def test_update_rest_call_success(request_type): "time_window_sec": 1600, }, "scaling_schedules": {}, + "stabilization_period_sec": 2553, }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_vm_extension_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_vm_extension_policies.py new file mode 100644 index 000000000000..fbdb820cbe6a --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_vm_extension_policies.py @@ -0,0 +1,5033 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.extended_operation as extended_operation # type: ignore +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1.services.global_vm_extension_policies import ( + GlobalVmExtensionPoliciesClient, + pagers, + transports, +) +from google.cloud.compute_v1.types import compute + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + custom_endpoint = ".custom" + + assert GlobalVmExtensionPoliciesClient._get_default_mtls_endpoint(None) is None + assert ( + GlobalVmExtensionPoliciesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + GlobalVmExtensionPoliciesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + GlobalVmExtensionPoliciesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + GlobalVmExtensionPoliciesClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + GlobalVmExtensionPoliciesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + GlobalVmExtensionPoliciesClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert GlobalVmExtensionPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert GlobalVmExtensionPoliciesClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert GlobalVmExtensionPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + GlobalVmExtensionPoliciesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert GlobalVmExtensionPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert GlobalVmExtensionPoliciesClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert GlobalVmExtensionPoliciesClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert GlobalVmExtensionPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + GlobalVmExtensionPoliciesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert GlobalVmExtensionPoliciesClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + GlobalVmExtensionPoliciesClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert GlobalVmExtensionPoliciesClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert ( + GlobalVmExtensionPoliciesClient._use_client_cert_effective() + is False + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert GlobalVmExtensionPoliciesClient._get_client_cert_source(None, False) is None + assert ( + GlobalVmExtensionPoliciesClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + GlobalVmExtensionPoliciesClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + GlobalVmExtensionPoliciesClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + GlobalVmExtensionPoliciesClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + GlobalVmExtensionPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GlobalVmExtensionPoliciesClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = GlobalVmExtensionPoliciesClient._DEFAULT_UNIVERSE + default_endpoint = ( + GlobalVmExtensionPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = GlobalVmExtensionPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + GlobalVmExtensionPoliciesClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + GlobalVmExtensionPoliciesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == GlobalVmExtensionPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GlobalVmExtensionPoliciesClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + GlobalVmExtensionPoliciesClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == GlobalVmExtensionPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GlobalVmExtensionPoliciesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == GlobalVmExtensionPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GlobalVmExtensionPoliciesClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + GlobalVmExtensionPoliciesClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + GlobalVmExtensionPoliciesClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + GlobalVmExtensionPoliciesClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + GlobalVmExtensionPoliciesClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + GlobalVmExtensionPoliciesClient._get_universe_domain(None, None) + == GlobalVmExtensionPoliciesClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + GlobalVmExtensionPoliciesClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = GlobalVmExtensionPoliciesClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = GlobalVmExtensionPoliciesClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (GlobalVmExtensionPoliciesClient, "rest"), + ], +) +def test_global_vm_extension_policies_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.GlobalVmExtensionPoliciesRestTransport, "rest"), + ], +) +def test_global_vm_extension_policies_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (GlobalVmExtensionPoliciesClient, "rest"), + ], +) +def test_global_vm_extension_policies_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_global_vm_extension_policies_client_get_transport_class(): + transport = GlobalVmExtensionPoliciesClient.get_transport_class() + available_transports = [ + transports.GlobalVmExtensionPoliciesRestTransport, + ] + assert transport in available_transports + + transport = GlobalVmExtensionPoliciesClient.get_transport_class("rest") + assert transport == transports.GlobalVmExtensionPoliciesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + GlobalVmExtensionPoliciesClient, + transports.GlobalVmExtensionPoliciesRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + GlobalVmExtensionPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GlobalVmExtensionPoliciesClient), +) +def test_global_vm_extension_policies_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + GlobalVmExtensionPoliciesClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + GlobalVmExtensionPoliciesClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + GlobalVmExtensionPoliciesClient, + transports.GlobalVmExtensionPoliciesRestTransport, + "rest", + "true", + ), + ( + GlobalVmExtensionPoliciesClient, + transports.GlobalVmExtensionPoliciesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + GlobalVmExtensionPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GlobalVmExtensionPoliciesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_global_vm_extension_policies_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [GlobalVmExtensionPoliciesClient]) +@mock.patch.object( + GlobalVmExtensionPoliciesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GlobalVmExtensionPoliciesClient), +) +def test_global_vm_extension_policies_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [GlobalVmExtensionPoliciesClient]) +@mock.patch.object( + GlobalVmExtensionPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GlobalVmExtensionPoliciesClient), +) +def test_global_vm_extension_policies_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = GlobalVmExtensionPoliciesClient._DEFAULT_UNIVERSE + default_endpoint = ( + GlobalVmExtensionPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = GlobalVmExtensionPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + GlobalVmExtensionPoliciesClient, + transports.GlobalVmExtensionPoliciesRestTransport, + "rest", + ), + ], +) +def test_global_vm_extension_policies_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + GlobalVmExtensionPoliciesClient, + transports.GlobalVmExtensionPoliciesRestTransport, + "rest", + None, + ), + ], +) +def test_global_vm_extension_policies_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_aggregated_list_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.aggregated_list in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.aggregated_list] = mock_rpc + + request = {} + client.aggregated_list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.aggregated_list(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_aggregated_list_rest_required_fields( + request_type=compute.AggregatedListGlobalVmExtensionPoliciesRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregated_list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregated_list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "include_all_scopes", + "max_results", + "order_by", + "page_token", + "return_partial_success", + "service_project_number", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.VmExtensionPolicyAggregatedListResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.VmExtensionPolicyAggregatedListResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.aggregated_list(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_aggregated_list_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.aggregated_list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "includeAllScopes", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + "serviceProjectNumber", + ) + ) + & set(("project",)) + ) + + +def test_aggregated_list_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.VmExtensionPolicyAggregatedListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.VmExtensionPolicyAggregatedListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.aggregated_list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/aggregated/vmExtensionPolicies" + % client.transport._host, + args[1], + ) + + +def test_aggregated_list_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.aggregated_list( + compute.AggregatedListGlobalVmExtensionPoliciesRequest(), + project="project_value", + ) + + +def test_aggregated_list_rest_pager(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + compute.VmExtensionPolicyAggregatedListResponse( + items={ + "a": compute.VmExtensionPoliciesScopedList(), + "b": compute.VmExtensionPoliciesScopedList(), + "c": compute.VmExtensionPoliciesScopedList(), + }, + next_page_token="abc", + ), + compute.VmExtensionPolicyAggregatedListResponse( + items={}, + next_page_token="def", + ), + compute.VmExtensionPolicyAggregatedListResponse( + items={ + "g": compute.VmExtensionPoliciesScopedList(), + }, + next_page_token="ghi", + ), + compute.VmExtensionPolicyAggregatedListResponse( + items={ + "h": compute.VmExtensionPoliciesScopedList(), + "i": compute.VmExtensionPoliciesScopedList(), + }, + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.VmExtensionPolicyAggregatedListResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project": "sample1"} + + pager = client.aggregated_list(request=sample_request) + + assert isinstance(pager.get("a"), compute.VmExtensionPoliciesScopedList) + assert pager.get("h") is None + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tuple) for i in results) + for result in results: + assert isinstance(result, tuple) + assert tuple(type(t) for t in result) == ( + str, + compute.VmExtensionPoliciesScopedList, + ) + + assert pager.get("a") is None + assert isinstance(pager.get("h"), compute.VmExtensionPoliciesScopedList) + + pages = list(client.aggregated_list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete] = mock_rpc + + request = {} + client.delete(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_rest_required_fields( + request_type=compute.DeleteGlobalVmExtensionPolicyRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["global_vm_extension_policy"] = "" + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["globalVmExtensionPolicy"] = "global_vm_extension_policy_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "globalVmExtensionPolicy" in jsonified_request + assert ( + jsonified_request["globalVmExtensionPolicy"] + == "global_vm_extension_policy_value" + ) + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "globalVmExtensionPolicy", + "globalVmExtensionPolicyRolloutOperationRolloutInputResource", + "project", + ) + ) + ) + + +def test_delete_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "global_vm_extension_policy": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + global_vm_extension_policy_rollout_operation_rollout_input_resource=compute.GlobalVmExtensionPolicyRolloutOperationRolloutInput( + conflict_behavior="conflict_behavior_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/vmExtensionPolicies/{global_vm_extension_policy}/delete" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete( + compute.DeleteGlobalVmExtensionPolicyRequest(), + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + global_vm_extension_policy_rollout_operation_rollout_input_resource=compute.GlobalVmExtensionPolicyRolloutOperationRolloutInput( + conflict_behavior="conflict_behavior_value" + ), + ) + + +def test_delete_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete] = mock_rpc + + request = {} + client.delete_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_unary_rest_required_fields( + request_type=compute.DeleteGlobalVmExtensionPolicyRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["global_vm_extension_policy"] = "" + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["globalVmExtensionPolicy"] = "global_vm_extension_policy_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "globalVmExtensionPolicy" in jsonified_request + assert ( + jsonified_request["globalVmExtensionPolicy"] + == "global_vm_extension_policy_value" + ) + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "globalVmExtensionPolicy", + "globalVmExtensionPolicyRolloutOperationRolloutInputResource", + "project", + ) + ) + ) + + +def test_delete_unary_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "global_vm_extension_policy": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + global_vm_extension_policy_rollout_operation_rollout_input_resource=compute.GlobalVmExtensionPolicyRolloutOperationRolloutInput( + conflict_behavior="conflict_behavior_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/vmExtensionPolicies/{global_vm_extension_policy}/delete" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_unary( + compute.DeleteGlobalVmExtensionPolicyRequest(), + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + global_vm_extension_policy_rollout_operation_rollout_input_resource=compute.GlobalVmExtensionPolicyRolloutOperationRolloutInput( + conflict_behavior="conflict_behavior_value" + ), + ) + + +def test_get_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get] = mock_rpc + + request = {} + client.get(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_rest_required_fields( + request_type=compute.GetGlobalVmExtensionPolicyRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["global_vm_extension_policy"] = "" + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["globalVmExtensionPolicy"] = "global_vm_extension_policy_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "globalVmExtensionPolicy" in jsonified_request + assert ( + jsonified_request["globalVmExtensionPolicy"] + == "global_vm_extension_policy_value" + ) + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.GlobalVmExtensionPolicy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.GlobalVmExtensionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "globalVmExtensionPolicy", + "project", + ) + ) + ) + + +def test_get_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.GlobalVmExtensionPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "global_vm_extension_policy": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.GlobalVmExtensionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/vmExtensionPolicies/{global_vm_extension_policy}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get( + compute.GetGlobalVmExtensionPolicyRequest(), + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + ) + + +def test_insert_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.insert] = mock_rpc + + request = {} + client.insert(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.insert(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_rest_required_fields( + request_type=compute.InsertGlobalVmExtensionPolicyRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_insert_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "globalVmExtensionPolicyResource", + "project", + ) + ) + ) + + +def test_insert_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + global_vm_extension_policy_resource=compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.insert(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/vmExtensionPolicies" + % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.insert( + compute.InsertGlobalVmExtensionPolicyRequest(), + project="project_value", + global_vm_extension_policy_resource=compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_insert_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.insert] = mock_rpc + + request = {} + client.insert_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.insert_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_unary_rest_required_fields( + request_type=compute.InsertGlobalVmExtensionPolicyRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "globalVmExtensionPolicyResource", + "project", + ) + ) + ) + + +def test_insert_unary_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + global_vm_extension_policy_resource=compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.insert_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/vmExtensionPolicies" + % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.insert_unary( + compute.InsertGlobalVmExtensionPolicyRequest(), + project="project_value", + global_vm_extension_policy_resource=compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_list_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list] = mock_rpc + + request = {} + client.list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_rest_required_fields( + request_type=compute.ListGlobalVmExtensionPoliciesRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "order_by", + "page_token", + "return_partial_success", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.GlobalVmExtensionPolicyList() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.GlobalVmExtensionPolicyList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("project",)) + ) + + +def test_list_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.GlobalVmExtensionPolicyList() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.GlobalVmExtensionPolicyList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/vmExtensionPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list( + compute.ListGlobalVmExtensionPoliciesRequest(), + project="project_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + compute.GlobalVmExtensionPolicyList( + items=[ + compute.GlobalVmExtensionPolicy(), + compute.GlobalVmExtensionPolicy(), + compute.GlobalVmExtensionPolicy(), + ], + next_page_token="abc", + ), + compute.GlobalVmExtensionPolicyList( + items=[], + next_page_token="def", + ), + compute.GlobalVmExtensionPolicyList( + items=[ + compute.GlobalVmExtensionPolicy(), + ], + next_page_token="ghi", + ), + compute.GlobalVmExtensionPolicyList( + items=[ + compute.GlobalVmExtensionPolicy(), + compute.GlobalVmExtensionPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.GlobalVmExtensionPolicyList.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project": "sample1"} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.GlobalVmExtensionPolicy) for i in results) + + pages = list(client.list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update] = mock_rpc + + request = {} + client.update(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_rest_required_fields( + request_type=compute.UpdateGlobalVmExtensionPolicyRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["global_vm_extension_policy"] = "" + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["globalVmExtensionPolicy"] = "global_vm_extension_policy_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "globalVmExtensionPolicy" in jsonified_request + assert ( + jsonified_request["globalVmExtensionPolicy"] + == "global_vm_extension_policy_value" + ) + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "globalVmExtensionPolicy", + "globalVmExtensionPolicyResource", + "project", + ) + ) + ) + + +def test_update_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "global_vm_extension_policy": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + global_vm_extension_policy_resource=compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/vmExtensionPolicies/{global_vm_extension_policy}" + % client.transport._host, + args[1], + ) + + +def test_update_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update( + compute.UpdateGlobalVmExtensionPolicyRequest(), + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + global_vm_extension_policy_resource=compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_update_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update] = mock_rpc + + request = {} + client.update_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_unary_rest_required_fields( + request_type=compute.UpdateGlobalVmExtensionPolicyRequest, +): + transport_class = transports.GlobalVmExtensionPoliciesRestTransport + + request_init = {} + request_init["global_vm_extension_policy"] = "" + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["globalVmExtensionPolicy"] = "global_vm_extension_policy_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "globalVmExtensionPolicy" in jsonified_request + assert ( + jsonified_request["globalVmExtensionPolicy"] + == "global_vm_extension_policy_value" + ) + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_unary_rest_unset_required_fields(): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "globalVmExtensionPolicy", + "globalVmExtensionPolicyResource", + "project", + ) + ) + ) + + +def test_update_unary_rest_flattened(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "global_vm_extension_policy": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + global_vm_extension_policy_resource=compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/vmExtensionPolicies/{global_vm_extension_policy}" + % client.transport._host, + args[1], + ) + + +def test_update_unary_rest_flattened_error(transport: str = "rest"): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_unary( + compute.UpdateGlobalVmExtensionPolicyRequest(), + project="project_value", + global_vm_extension_policy="global_vm_extension_policy_value", + global_vm_extension_policy_resource=compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GlobalVmExtensionPoliciesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GlobalVmExtensionPoliciesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GlobalVmExtensionPoliciesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GlobalVmExtensionPoliciesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GlobalVmExtensionPoliciesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GlobalVmExtensionPoliciesRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = GlobalVmExtensionPoliciesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_aggregated_list_rest_bad_request( + request_type=compute.AggregatedListGlobalVmExtensionPoliciesRequest, +): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.aggregated_list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AggregatedListGlobalVmExtensionPoliciesRequest, + dict, + ], +) +def test_aggregated_list_rest_call_success(request_type): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.VmExtensionPolicyAggregatedListResponse( + etag="etag_value", + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.VmExtensionPolicyAggregatedListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.aggregated_list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AggregatedListPager) + assert response.etag == "etag_value" + assert response.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_aggregated_list_rest_interceptors(null_interceptor): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GlobalVmExtensionPoliciesRestInterceptor(), + ) + client = GlobalVmExtensionPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "post_aggregated_list" + ) as post, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, + "post_aggregated_list_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "pre_aggregated_list" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AggregatedListGlobalVmExtensionPoliciesRequest.pb( + compute.AggregatedListGlobalVmExtensionPoliciesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.VmExtensionPolicyAggregatedListResponse.to_json( + compute.VmExtensionPolicyAggregatedListResponse() + ) + req.return_value.content = return_value + + request = compute.AggregatedListGlobalVmExtensionPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.VmExtensionPolicyAggregatedListResponse() + post_with_metadata.return_value = ( + compute.VmExtensionPolicyAggregatedListResponse(), + metadata, + ) + + client.aggregated_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_rest_bad_request( + request_type=compute.DeleteGlobalVmExtensionPolicyRequest, +): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "global_vm_extension_policy": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteGlobalVmExtensionPolicyRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "global_vm_extension_policy": "sample2"} + request_init[ + "global_vm_extension_policy_rollout_operation_rollout_input_resource" + ] = { + "conflict_behavior": "conflict_behavior_value", + "name": "name_value", + "predefined_rollout_plan": "predefined_rollout_plan_value", + "retry_uuid": "retry_uuid_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.DeleteGlobalVmExtensionPolicyRequest.meta.fields[ + "global_vm_extension_policy_rollout_operation_rollout_input_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "global_vm_extension_policy_rollout_operation_rollout_input_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, + len( + request_init[ + "global_vm_extension_policy_rollout_operation_rollout_input_resource" + ][field] + ), + ): + del request_init[ + "global_vm_extension_policy_rollout_operation_rollout_input_resource" + ][field][i][subfield] + else: + del request_init[ + "global_vm_extension_policy_rollout_operation_rollout_input_resource" + ][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GlobalVmExtensionPoliciesRestInterceptor(), + ) + client = GlobalVmExtensionPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "post_delete" + ) as post, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, + "post_delete_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "pre_delete" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteGlobalVmExtensionPolicyRequest.pb( + compute.DeleteGlobalVmExtensionPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteGlobalVmExtensionPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rest_bad_request(request_type=compute.GetGlobalVmExtensionPolicyRequest): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "global_vm_extension_policy": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetGlobalVmExtensionPolicyRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "global_vm_extension_policy": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.GlobalVmExtensionPolicy( + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + kind="kind_value", + name="name_value", + priority=898, + scoped_resource_status="scoped_resource_status_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + update_timestamp="update_timestamp_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.GlobalVmExtensionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.GlobalVmExtensionPolicy) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.priority == 898 + assert response.scoped_resource_status == "scoped_resource_status_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.update_timestamp == "update_timestamp_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GlobalVmExtensionPoliciesRestInterceptor(), + ) + client = GlobalVmExtensionPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "post_get" + ) as post, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, + "post_get_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "pre_get" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetGlobalVmExtensionPolicyRequest.pb( + compute.GetGlobalVmExtensionPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.GlobalVmExtensionPolicy.to_json( + compute.GlobalVmExtensionPolicy() + ) + req.return_value.content = return_value + + request = compute.GetGlobalVmExtensionPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.GlobalVmExtensionPolicy() + post_with_metadata.return_value = compute.GlobalVmExtensionPolicy(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_insert_rest_bad_request( + request_type=compute.InsertGlobalVmExtensionPolicyRequest, +): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.insert(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertGlobalVmExtensionPolicyRequest, + dict, + ], +) +def test_insert_rest_call_success(request_type): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request_init["global_vm_extension_policy_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "extension_policies": {}, + "id": 205, + "instance_selectors": [{"label_selector": {"inclusion_labels": {}}}], + "kind": "kind_value", + "name": "name_value", + "priority": 898, + "rollout_operation": { + "rollout_input": { + "conflict_behavior": "conflict_behavior_value", + "name": "name_value", + "predefined_rollout_plan": "predefined_rollout_plan_value", + "retry_uuid": "retry_uuid_value", + }, + "rollout_status": { + "current_rollouts": [ + { + "location_rollout_status": {}, + "rollout": "rollout_value", + "rollout_plan": "rollout_plan_value", + "state": "state_value", + } + ], + "previous_rollout": {}, + }, + }, + "scoped_resource_status": "scoped_resource_status_value", + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "update_timestamp": "update_timestamp_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.InsertGlobalVmExtensionPolicyRequest.meta.fields[ + "global_vm_extension_policy_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "global_vm_extension_policy_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["global_vm_extension_policy_resource"][field]) + ): + del request_init["global_vm_extension_policy_resource"][field][i][ + subfield + ] + else: + del request_init["global_vm_extension_policy_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.insert(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_rest_interceptors(null_interceptor): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GlobalVmExtensionPoliciesRestInterceptor(), + ) + client = GlobalVmExtensionPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "post_insert" + ) as post, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, + "post_insert_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "pre_insert" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.InsertGlobalVmExtensionPolicyRequest.pb( + compute.InsertGlobalVmExtensionPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.InsertGlobalVmExtensionPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.insert( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_rest_bad_request( + request_type=compute.ListGlobalVmExtensionPoliciesRequest, +): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListGlobalVmExtensionPoliciesRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.GlobalVmExtensionPolicyList( + etag="etag_value", + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.GlobalVmExtensionPolicyList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPager) + assert response.etag == "etag_value" + assert response.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GlobalVmExtensionPoliciesRestInterceptor(), + ) + client = GlobalVmExtensionPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "post_list" + ) as post, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, + "post_list_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "pre_list" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListGlobalVmExtensionPoliciesRequest.pb( + compute.ListGlobalVmExtensionPoliciesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.GlobalVmExtensionPolicyList.to_json( + compute.GlobalVmExtensionPolicyList() + ) + req.return_value.content = return_value + + request = compute.ListGlobalVmExtensionPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.GlobalVmExtensionPolicyList() + post_with_metadata.return_value = ( + compute.GlobalVmExtensionPolicyList(), + metadata, + ) + + client.list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_rest_bad_request( + request_type=compute.UpdateGlobalVmExtensionPolicyRequest, +): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "global_vm_extension_policy": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.UpdateGlobalVmExtensionPolicyRequest, + dict, + ], +) +def test_update_rest_call_success(request_type): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "global_vm_extension_policy": "sample2"} + request_init["global_vm_extension_policy_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "extension_policies": {}, + "id": 205, + "instance_selectors": [{"label_selector": {"inclusion_labels": {}}}], + "kind": "kind_value", + "name": "name_value", + "priority": 898, + "rollout_operation": { + "rollout_input": { + "conflict_behavior": "conflict_behavior_value", + "name": "name_value", + "predefined_rollout_plan": "predefined_rollout_plan_value", + "retry_uuid": "retry_uuid_value", + }, + "rollout_status": { + "current_rollouts": [ + { + "location_rollout_status": {}, + "rollout": "rollout_value", + "rollout_plan": "rollout_plan_value", + "state": "state_value", + } + ], + "previous_rollout": {}, + }, + }, + "scoped_resource_status": "scoped_resource_status_value", + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "update_timestamp": "update_timestamp_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.UpdateGlobalVmExtensionPolicyRequest.meta.fields[ + "global_vm_extension_policy_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "global_vm_extension_policy_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["global_vm_extension_policy_resource"][field]) + ): + del request_init["global_vm_extension_policy_resource"][field][i][ + subfield + ] + else: + del request_init["global_vm_extension_policy_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_rest_interceptors(null_interceptor): + transport = transports.GlobalVmExtensionPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GlobalVmExtensionPoliciesRestInterceptor(), + ) + client = GlobalVmExtensionPoliciesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "post_update" + ) as post, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, + "post_update_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.GlobalVmExtensionPoliciesRestInterceptor, "pre_update" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.UpdateGlobalVmExtensionPolicyRequest.pb( + compute.UpdateGlobalVmExtensionPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.UpdateGlobalVmExtensionPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.update( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_aggregated_list_empty_call_rest(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.aggregated_list), "__call__") as call: + client.aggregated_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.AggregatedListGlobalVmExtensionPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_unary_empty_call_rest(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete), "__call__") as call: + client.delete_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.DeleteGlobalVmExtensionPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_empty_call_rest(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get), "__call__") as call: + client.get(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetGlobalVmExtensionPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_unary_empty_call_rest(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.insert), "__call__") as call: + client.insert_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.InsertGlobalVmExtensionPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_empty_call_rest(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list), "__call__") as call: + client.list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ListGlobalVmExtensionPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_unary_empty_call_rest(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update), "__call__") as call: + client.update_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.UpdateGlobalVmExtensionPolicyRequest() + + assert args[0] == request_msg + + +def test_global_vm_extension_policies_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GlobalVmExtensionPoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_global_vm_extension_policies_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.global_vm_extension_policies.transports.GlobalVmExtensionPoliciesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GlobalVmExtensionPoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "aggregated_list", + "delete", + "get", + "insert", + "list", + "update", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_global_vm_extension_policies_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.compute_v1.services.global_vm_extension_policies.transports.GlobalVmExtensionPoliciesTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalVmExtensionPoliciesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_global_vm_extension_policies_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.compute_v1.services.global_vm_extension_policies.transports.GlobalVmExtensionPoliciesTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GlobalVmExtensionPoliciesTransport() + adc.assert_called_once() + + +def test_global_vm_extension_policies_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + GlobalVmExtensionPoliciesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_global_vm_extension_policies_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.GlobalVmExtensionPoliciesRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_global_vm_extension_policies_host_no_port(transport_name): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_global_vm_extension_policies_host_with_port(transport_name): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_global_vm_extension_policies_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GlobalVmExtensionPoliciesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GlobalVmExtensionPoliciesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.aggregated_list._session + session2 = client2.transport.aggregated_list._session + assert session1 != session2 + session1 = client1.transport.delete._session + session2 = client2.transport.delete._session + assert session1 != session2 + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.insert._session + session2 = client2.transport.insert._session + assert session1 != session2 + session1 = client1.transport.list._session + session2 = client2.transport.list._session + assert session1 != session2 + session1 = client1.transport.update._session + session2 = client2.transport.update._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = GlobalVmExtensionPoliciesClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = GlobalVmExtensionPoliciesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalVmExtensionPoliciesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = GlobalVmExtensionPoliciesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = GlobalVmExtensionPoliciesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalVmExtensionPoliciesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = GlobalVmExtensionPoliciesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = GlobalVmExtensionPoliciesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalVmExtensionPoliciesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = GlobalVmExtensionPoliciesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = GlobalVmExtensionPoliciesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalVmExtensionPoliciesClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = GlobalVmExtensionPoliciesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = GlobalVmExtensionPoliciesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GlobalVmExtensionPoliciesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.GlobalVmExtensionPoliciesTransport, "_prep_wrapped_messages" + ) as prep: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.GlobalVmExtensionPoliciesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = GlobalVmExtensionPoliciesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = GlobalVmExtensionPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + GlobalVmExtensionPoliciesClient, + transports.GlobalVmExtensionPoliciesRestTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py index de5b7c1d8b15..c277dd20ad22 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py @@ -1314,6 +1314,400 @@ def test_get_rest_flattened_error(transport: str = "rest"): ) +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_iam_policy_rest_required_fields( + request_type=compute.GetIamPolicyLicenseCodeRequest, +): + transport_class = transports.LicenseCodesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("options_requested_policy_version",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.LicenseCodesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("optionsRequestedPolicyVersion",)) + & set( + ( + "project", + "resource", + ) + ) + ) + + +def test_get_iam_policy_rest_flattened(): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "resource": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/licenseCodes/{resource}/getIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + compute.GetIamPolicyLicenseCodeRequest(), + project="project_value", + resource="resource_value", + ) + + +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_iam_policy_rest_required_fields( + request_type=compute.SetIamPolicyLicenseCodeRequest, +): + transport_class = transports.LicenseCodesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.LicenseCodesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "globalSetPolicyRequestResource", + "project", + "resource", + ) + ) + ) + + +def test_set_iam_policy_rest_flattened(): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "resource": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + resource="resource_value", + global_set_policy_request_resource=compute.GlobalSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/licenseCodes/{resource}/setIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + compute.SetIamPolicyLicenseCodeRequest(), + project="project_value", + resource="resource_value", + global_set_policy_request_resource=compute.GlobalSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + + def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1539,73 +1933,367 @@ def test_credentials_transport_error(): transport=transport, ) - # It is an error to provide an api_key and a transport instance. - transport = transports.LicenseCodesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LicenseCodesClient( - client_options=options, - transport=transport, + # It is an error to provide an api_key and a transport instance. + transport = transports.LicenseCodesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LicenseCodesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LicenseCodesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LicenseCodesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LicenseCodesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LicenseCodesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LicenseCodesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LicenseCodesRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = LicenseCodesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetLicenseCodeRequest): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "license_code": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetLicenseCodeRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "license_code": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.LicenseCode( + allowed_replacement_licenses=["allowed_replacement_licenses_value"], + appendable_to_disk=True, + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + incompatible_licenses=["incompatible_licenses_value"], + kind="kind_value", + multi_tenant_only=True, + name="name_value", + os_license=True, + removable_from_disk=True, + required_coattached_licenses=["required_coattached_licenses_value"], + self_link="self_link_value", + sole_tenant_only=True, + state="state_value", + transferable=True, + update_timestamp="update_timestamp_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.LicenseCode.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.LicenseCode) + assert response.allowed_replacement_licenses == [ + "allowed_replacement_licenses_value" + ] + assert response.appendable_to_disk is True + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.id == 205 + assert response.incompatible_licenses == ["incompatible_licenses_value"] + assert response.kind == "kind_value" + assert response.multi_tenant_only is True + assert response.name == "name_value" + assert response.os_license is True + assert response.removable_from_disk is True + assert response.required_coattached_licenses == [ + "required_coattached_licenses_value" + ] + assert response.self_link == "self_link_value" + assert response.sole_tenant_only is True + assert response.state == "state_value" + assert response.transferable is True + assert response.update_timestamp == "update_timestamp_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.LicenseCodesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LicenseCodesRestInterceptor(), + ) + client = LicenseCodesClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.LicenseCodesRestInterceptor, "post_get") as post, + mock.patch.object( + transports.LicenseCodesRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LicenseCodesRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetLicenseCodeRequest.pb(compute.GetLicenseCodeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.LicenseCode.to_json(compute.LicenseCode()) + req.return_value.content = return_value + + request = compute.GetLicenseCodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.LicenseCode() + post_with_metadata.return_value = compute.LicenseCode(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=compute.GetIamPolicyLicenseCodeRequest, +): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "resource": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetIamPolicyLicenseCodeRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "resource": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LicenseCodesClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - # It is an error to provide scopes and a transport instance. - transport = transports.LicenseCodesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LicenseCodesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_iam_policy(request) + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.LicenseCodesRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.LicenseCodesRestInterceptor(), ) client = LicenseCodesClient(transport=transport) - assert client.transport is transport + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.LicenseCodesRestInterceptor, "post_get_iam_policy" + ) as post, + mock.patch.object( + transports.LicenseCodesRestInterceptor, "post_get_iam_policy_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.LicenseCodesRestInterceptor, "pre_get_iam_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetIamPolicyLicenseCodeRequest.pb( + compute.GetIamPolicyLicenseCodeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Policy.to_json(compute.Policy()) + req.return_value.content = return_value -@pytest.mark.parametrize( - "transport_class", - [ - transports.LicenseCodesRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + request = compute.GetIamPolicyLicenseCodeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Policy() + post_with_metadata.return_value = compute.Policy(), metadata + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = LicenseCodesClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_rest_bad_request(request_type=compute.GetLicenseCodeRequest): +def test_set_iam_policy_rest_bad_request( + request_type=compute.SetIamPolicyLicenseCodeRequest, +): client = LicenseCodesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "license_code": "sample2"} + request_init = {"project": "sample1", "resource": "sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -1621,37 +2309,148 @@ def test_get_rest_bad_request(request_type=compute.GetLicenseCodeRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get(request) + client.set_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - compute.GetLicenseCodeRequest, + compute.SetIamPolicyLicenseCodeRequest, dict, ], ) -def test_get_rest_call_success(request_type): +def test_set_iam_policy_rest_call_success(request_type): client = LicenseCodesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "license_code": "sample2"} + request_init = {"project": "sample1", "resource": "sample2"} + request_init["global_set_policy_request_resource"] = { + "bindings": [ + { + "binding_id": "binding_id_value", + "condition": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "members": ["members_value1", "members_value2"], + "role": "role_value", + } + ], + "etag": "etag_value", + "policy": { + "audit_configs": [ + { + "audit_log_configs": [ + { + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "ignore_child_exemptions": True, + "log_type": "log_type_value", + } + ], + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "service": "service_value", + } + ], + "bindings": {}, + "etag": "etag_value", + "iam_owned": True, + "version": 774, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetIamPolicyLicenseCodeRequest.meta.fields[ + "global_set_policy_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "global_set_policy_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["global_set_policy_request_resource"][field]) + ): + del request_init["global_set_policy_request_resource"][field][i][ + subfield + ] + else: + del request_init["global_set_policy_request_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.LicenseCode( - creation_timestamp="creation_timestamp_value", - description="description_value", - id=205, - kind="kind_value", - name="name_value", - self_link="self_link_value", - state="state_value", - transferable=True, + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, ) # Wrap the value into a proper Response obj @@ -1659,27 +2458,22 @@ def test_get_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.LicenseCode.pb(return_value) + return_value = compute.Policy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get(request) + response = client.set_iam_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.LicenseCode) - assert response.creation_timestamp == "creation_timestamp_value" - assert response.description == "description_value" - assert response.id == 205 - assert response.kind == "kind_value" - assert response.name == "name_value" - assert response.self_link == "self_link_value" - assert response.state == "state_value" - assert response.transferable is True + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_rest_interceptors(null_interceptor): +def test_set_iam_policy_rest_interceptors(null_interceptor): transport = transports.LicenseCodesRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -1691,16 +2485,22 @@ def test_get_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.LicenseCodesRestInterceptor, "post_get") as post, mock.patch.object( - transports.LicenseCodesRestInterceptor, "post_get_with_metadata" + transports.LicenseCodesRestInterceptor, "post_set_iam_policy" + ) as post, + mock.patch.object( + transports.LicenseCodesRestInterceptor, "post_set_iam_policy_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.LicenseCodesRestInterceptor, "pre_get") as pre, + mock.patch.object( + transports.LicenseCodesRestInterceptor, "pre_set_iam_policy" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetLicenseCodeRequest.pb(compute.GetLicenseCodeRequest()) + pb_message = compute.SetIamPolicyLicenseCodeRequest.pb( + compute.SetIamPolicyLicenseCodeRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -1711,19 +2511,19 @@ def test_get_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = compute.LicenseCode.to_json(compute.LicenseCode()) + return_value = compute.Policy.to_json(compute.Policy()) req.return_value.content = return_value - request = compute.GetLicenseCodeRequest() + request = compute.SetIamPolicyLicenseCodeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.LicenseCode() - post_with_metadata.return_value = compute.LicenseCode(), metadata + post.return_value = compute.Policy() + post_with_metadata.return_value = compute.Policy(), metadata - client.get( + client.set_iam_policy( request, metadata=[ ("key", "val"), @@ -1974,6 +2774,46 @@ def test_get_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetIamPolicyLicenseCodeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = LicenseCodesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.SetIamPolicyLicenseCodeRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_test_iam_permissions_empty_call_rest(): @@ -2019,6 +2859,8 @@ def test_license_codes_base_transport(): # raise NotImplementedError. methods = ( "get", + "get_iam_policy", + "set_iam_policy", "test_iam_permissions", ) for method in methods: @@ -2057,7 +2899,6 @@ def test_license_codes_base_transport_with_credentials_file(): "credentials.json", scopes=None, default_scopes=( - "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ), @@ -2087,7 +2928,6 @@ def test_license_codes_auth_adc(): adc.assert_called_once_with( scopes=None, default_scopes=( - "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ), @@ -2168,6 +3008,12 @@ def test_license_codes_client_transport_session_collision(transport_name): session1 = client1.transport.get._session session2 = client2.transport.get._session assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 session1 = client1.transport.test_iam_permissions._session session2 = client2.transport.test_iam_permissions._session assert session1 != session2 diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py index 98699be6bb66..b3fefdb89e2f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py @@ -1517,6 +1517,434 @@ def test_add_peering_unary_rest_flattened_error(transport: str = "rest"): ) +def test_cancel_request_remove_peering_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.cancel_request_remove_peering + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.cancel_request_remove_peering + ] = mock_rpc + + request = {} + client.cancel_request_remove_peering(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.cancel_request_remove_peering(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_cancel_request_remove_peering_rest_required_fields( + request_type=compute.CancelRequestRemovePeeringNetworkRequest, +): + transport_class = transports.NetworksRestTransport + + request_init = {} + request_init["network"] = "" + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel_request_remove_peering._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["network"] = "network_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel_request_remove_peering._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "network" in jsonified_request + assert jsonified_request["network"] == "network_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_request_remove_peering(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_cancel_request_remove_peering_rest_unset_required_fields(): + transport = transports.NetworksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.cancel_request_remove_peering._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "network", + "networksCancelRequestRemovePeeringRequestResource", + "project", + ) + ) + ) + + +def test_cancel_request_remove_peering_rest_flattened(): + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "network": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + network="network_value", + networks_cancel_request_remove_peering_request_resource=compute.NetworksCancelRequestRemovePeeringRequest( + name="name_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.cancel_request_remove_peering(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/networks/{network}/cancelRequestRemovePeering" + % client.transport._host, + args[1], + ) + + +def test_cancel_request_remove_peering_rest_flattened_error(transport: str = "rest"): + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.cancel_request_remove_peering( + compute.CancelRequestRemovePeeringNetworkRequest(), + project="project_value", + network="network_value", + networks_cancel_request_remove_peering_request_resource=compute.NetworksCancelRequestRemovePeeringRequest( + name="name_value" + ), + ) + + +def test_cancel_request_remove_peering_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.cancel_request_remove_peering + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.cancel_request_remove_peering + ] = mock_rpc + + request = {} + client.cancel_request_remove_peering_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.cancel_request_remove_peering_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_cancel_request_remove_peering_unary_rest_required_fields( + request_type=compute.CancelRequestRemovePeeringNetworkRequest, +): + transport_class = transports.NetworksRestTransport + + request_init = {} + request_init["network"] = "" + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel_request_remove_peering._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["network"] = "network_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel_request_remove_peering._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "network" in jsonified_request + assert jsonified_request["network"] == "network_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_request_remove_peering_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_cancel_request_remove_peering_unary_rest_unset_required_fields(): + transport = transports.NetworksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.cancel_request_remove_peering._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "network", + "networksCancelRequestRemovePeeringRequestResource", + "project", + ) + ) + ) + + +def test_cancel_request_remove_peering_unary_rest_flattened(): + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "network": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + network="network_value", + networks_cancel_request_remove_peering_request_resource=compute.NetworksCancelRequestRemovePeeringRequest( + name="name_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.cancel_request_remove_peering_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/networks/{network}/cancelRequestRemovePeering" + % client.transport._host, + args[1], + ) + + +def test_cancel_request_remove_peering_unary_rest_flattened_error( + transport: str = "rest", +): + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.cancel_request_remove_peering_unary( + compute.CancelRequestRemovePeeringNetworkRequest(), + project="project_value", + network="network_value", + networks_cancel_request_remove_peering_request_resource=compute.NetworksCancelRequestRemovePeeringRequest( + name="name_value" + ), + ) + + def test_delete_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5633,6 +6061,262 @@ def test_add_peering_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_cancel_request_remove_peering_rest_bad_request( + request_type=compute.CancelRequestRemovePeeringNetworkRequest, +): + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "network": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_request_remove_peering(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CancelRequestRemovePeeringNetworkRequest, + dict, + ], +) +def test_cancel_request_remove_peering_rest_call_success(request_type): + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "network": "sample2"} + request_init["networks_cancel_request_remove_peering_request_resource"] = { + "name": "name_value" + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.CancelRequestRemovePeeringNetworkRequest.meta.fields[ + "networks_cancel_request_remove_peering_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "networks_cancel_request_remove_peering_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, + len( + request_init[ + "networks_cancel_request_remove_peering_request_resource" + ][field] + ), + ): + del request_init[ + "networks_cancel_request_remove_peering_request_resource" + ][field][i][subfield] + else: + del request_init[ + "networks_cancel_request_remove_peering_request_resource" + ][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.cancel_request_remove_peering(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_request_remove_peering_rest_interceptors(null_interceptor): + transport = transports.NetworksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworksRestInterceptor(), + ) + client = NetworksClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.NetworksRestInterceptor, "post_cancel_request_remove_peering" + ) as post, + mock.patch.object( + transports.NetworksRestInterceptor, + "post_cancel_request_remove_peering_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NetworksRestInterceptor, "pre_cancel_request_remove_peering" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CancelRequestRemovePeeringNetworkRequest.pb( + compute.CancelRequestRemovePeeringNetworkRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.CancelRequestRemovePeeringNetworkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.cancel_request_remove_peering( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_delete_rest_bad_request(request_type=compute.DeleteNetworkRequest): client = NetworksClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -7905,6 +8589,28 @@ def test_add_peering_unary_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_cancel_request_remove_peering_unary_empty_call_rest(): + client = NetworksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_request_remove_peering), "__call__" + ) as call: + client.cancel_request_remove_peering_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CancelRequestRemovePeeringNetworkRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_delete_unary_empty_call_rest(): @@ -8156,6 +8862,7 @@ def test_networks_base_transport(): # raise NotImplementedError. methods = ( "add_peering", + "cancel_request_remove_peering", "delete", "get", "get_effective_firewalls", @@ -8313,6 +9020,9 @@ def test_networks_client_transport_session_collision(transport_name): session1 = client1.transport.add_peering._session session2 = client2.transport.add_peering._session assert session1 != session2 + session1 = client1.transport.cancel_request_remove_peering._session + session2 = client2.transport.cancel_request_remove_peering._session + assert session1 != session2 session1 = client1.transport.delete._session session2 = client2.transport.delete._session assert session1 != session2 diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py index 0a6fcec95039..5b15b2dffb9b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py @@ -4016,6 +4016,7 @@ def test_insert_rest_call_success(request_type): "time_window_sec": 1600, }, "scaling_schedules": {}, + "stabilization_period_sec": 2553, }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", @@ -4435,6 +4436,7 @@ def test_patch_rest_call_success(request_type): "time_window_sec": 1600, }, "scaling_schedules": {}, + "stabilization_period_sec": 2553, }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", @@ -4927,6 +4929,7 @@ def test_update_rest_call_success(request_type): "time_window_sec": 1600, }, "scaling_schedules": {}, + "stabilization_period_sec": 2553, }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_policies.py index a8af7766ddfa..e69ff5b99602 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_policies.py @@ -3422,6 +3422,7 @@ def test_get_rest_call_success(request_type): kind="kind_value", min_tls_version="min_tls_version_value", name="name_value", + post_quantum_key_exchange="post_quantum_key_exchange_value", profile="profile_value", region="region_value", self_link="self_link_value", @@ -3450,6 +3451,7 @@ def test_get_rest_call_success(request_type): assert response.kind == "kind_value" assert response.min_tls_version == "min_tls_version_value" assert response.name == "name_value" + assert response.post_quantum_key_exchange == "post_quantum_key_exchange_value" assert response.profile == "profile_value" assert response.region == "region_value" assert response.self_link == "self_link_value" @@ -3567,6 +3569,7 @@ def test_insert_rest_call_success(request_type): "kind": "kind_value", "min_tls_version": "min_tls_version_value", "name": "name_value", + "post_quantum_key_exchange": "post_quantum_key_exchange_value", "profile": "profile_value", "region": "region_value", "self_link": "self_link_value", @@ -4095,6 +4098,7 @@ def test_patch_rest_call_success(request_type): "kind": "kind_value", "min_tls_version": "min_tls_version_value", "name": "name_value", + "post_quantum_key_exchange": "post_quantum_key_exchange_value", "profile": "profile_value", "region": "region_value", "self_link": "self_link_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollout_plans.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollout_plans.py new file mode 100644 index 000000000000..c7b8233d3697 --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollout_plans.py @@ -0,0 +1,3635 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.extended_operation as extended_operation # type: ignore +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1.services.rollout_plans import ( + RolloutPlansClient, + pagers, + transports, +) +from google.cloud.compute_v1.types import compute + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + custom_endpoint = ".custom" + + assert RolloutPlansClient._get_default_mtls_endpoint(None) is None + assert ( + RolloutPlansClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + RolloutPlansClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RolloutPlansClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RolloutPlansClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert RolloutPlansClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + RolloutPlansClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert RolloutPlansClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RolloutPlansClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RolloutPlansClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + RolloutPlansClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert RolloutPlansClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RolloutPlansClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RolloutPlansClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RolloutPlansClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RolloutPlansClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert RolloutPlansClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert RolloutPlansClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert RolloutPlansClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RolloutPlansClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert RolloutPlansClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert RolloutPlansClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert RolloutPlansClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert RolloutPlansClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert RolloutPlansClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert RolloutPlansClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + RolloutPlansClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert RolloutPlansClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert RolloutPlansClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RolloutPlansClient._get_client_cert_source(None, False) is None + assert ( + RolloutPlansClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + RolloutPlansClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + RolloutPlansClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RolloutPlansClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + RolloutPlansClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RolloutPlansClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RolloutPlansClient._DEFAULT_UNIVERSE + default_endpoint = RolloutPlansClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RolloutPlansClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + RolloutPlansClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RolloutPlansClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RolloutPlansClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RolloutPlansClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + RolloutPlansClient._get_api_endpoint(None, None, default_universe, "always") + == RolloutPlansClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RolloutPlansClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RolloutPlansClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RolloutPlansClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + RolloutPlansClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + RolloutPlansClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + RolloutPlansClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + RolloutPlansClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RolloutPlansClient._get_universe_domain(None, None) + == RolloutPlansClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + RolloutPlansClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = RolloutPlansClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = RolloutPlansClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RolloutPlansClient, "rest"), + ], +) +def test_rollout_plans_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.RolloutPlansRestTransport, "rest"), + ], +) +def test_rollout_plans_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RolloutPlansClient, "rest"), + ], +) +def test_rollout_plans_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_rollout_plans_client_get_transport_class(): + transport = RolloutPlansClient.get_transport_class() + available_transports = [ + transports.RolloutPlansRestTransport, + ] + assert transport in available_transports + + transport = RolloutPlansClient.get_transport_class("rest") + assert transport == transports.RolloutPlansRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RolloutPlansClient, transports.RolloutPlansRestTransport, "rest"), + ], +) +@mock.patch.object( + RolloutPlansClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RolloutPlansClient), +) +def test_rollout_plans_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RolloutPlansClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RolloutPlansClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (RolloutPlansClient, transports.RolloutPlansRestTransport, "rest", "true"), + (RolloutPlansClient, transports.RolloutPlansRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + RolloutPlansClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RolloutPlansClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_rollout_plans_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [RolloutPlansClient]) +@mock.patch.object( + RolloutPlansClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RolloutPlansClient) +) +def test_rollout_plans_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [RolloutPlansClient]) +@mock.patch.object( + RolloutPlansClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RolloutPlansClient), +) +def test_rollout_plans_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RolloutPlansClient._DEFAULT_UNIVERSE + default_endpoint = RolloutPlansClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RolloutPlansClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RolloutPlansClient, transports.RolloutPlansRestTransport, "rest"), + ], +) +def test_rollout_plans_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (RolloutPlansClient, transports.RolloutPlansRestTransport, "rest", None), + ], +) +def test_rollout_plans_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_delete_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete] = mock_rpc + + request = {} + client.delete(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_rest_required_fields(request_type=compute.DeleteRolloutPlanRequest): + transport_class = transports.RolloutPlansRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout_plan"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rolloutPlan"] = "rollout_plan_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rolloutPlan" in jsonified_request + assert jsonified_request["rolloutPlan"] == "rollout_plan_value" + + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_rest_unset_required_fields(): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "rolloutPlan", + ) + ) + ) + + +def test_delete_rest_flattened(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout_plan": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout_plan="rollout_plan_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rolloutPlans/{rollout_plan}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete( + compute.DeleteRolloutPlanRequest(), + project="project_value", + rollout_plan="rollout_plan_value", + ) + + +def test_delete_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete] = mock_rpc + + request = {} + client.delete_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_unary_rest_required_fields( + request_type=compute.DeleteRolloutPlanRequest, +): + transport_class = transports.RolloutPlansRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout_plan"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rolloutPlan"] = "rollout_plan_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rolloutPlan" in jsonified_request + assert jsonified_request["rolloutPlan"] == "rollout_plan_value" + + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "rolloutPlan", + ) + ) + ) + + +def test_delete_unary_rest_flattened(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout_plan": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout_plan="rollout_plan_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rolloutPlans/{rollout_plan}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_unary( + compute.DeleteRolloutPlanRequest(), + project="project_value", + rollout_plan="rollout_plan_value", + ) + + +def test_get_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get] = mock_rpc + + request = {} + client.get(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_rest_required_fields(request_type=compute.GetRolloutPlanRequest): + transport_class = transports.RolloutPlansRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout_plan"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rolloutPlan"] = "rollout_plan_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rolloutPlan" in jsonified_request + assert jsonified_request["rolloutPlan"] == "rollout_plan_value" + + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlan() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.RolloutPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "rolloutPlan", + ) + ) + ) + + +def test_get_rest_flattened(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlan() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout_plan": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout_plan="rollout_plan_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.RolloutPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rolloutPlans/{rollout_plan}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get( + compute.GetRolloutPlanRequest(), + project="project_value", + rollout_plan="rollout_plan_value", + ) + + +def test_insert_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.insert] = mock_rpc + + request = {} + client.insert(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.insert(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_rest_required_fields(request_type=compute.InsertRolloutPlanRequest): + transport_class = transports.RolloutPlansRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_insert_rest_unset_required_fields(): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "rolloutPlanResource", + ) + ) + ) + + +def test_insert_rest_flattened(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout_plan_resource=compute.RolloutPlan( + creation_timestamp="creation_timestamp_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.insert(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rolloutPlans" + % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.insert( + compute.InsertRolloutPlanRequest(), + project="project_value", + rollout_plan_resource=compute.RolloutPlan( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_insert_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.insert in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.insert] = mock_rpc + + request = {} + client.insert_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.insert_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_insert_unary_rest_required_fields( + request_type=compute.InsertRolloutPlanRequest, +): + transport_class = transports.RolloutPlansRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.insert_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "rolloutPlanResource", + ) + ) + ) + + +def test_insert_unary_rest_flattened(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout_plan_resource=compute.RolloutPlan( + creation_timestamp="creation_timestamp_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.insert_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rolloutPlans" + % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.insert_unary( + compute.InsertRolloutPlanRequest(), + project="project_value", + rollout_plan_resource=compute.RolloutPlan( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_list_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list] = mock_rpc + + request = {} + client.list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_rest_required_fields(request_type=compute.ListRolloutPlansRequest): + transport_class = transports.RolloutPlansRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "order_by", + "page_token", + "return_partial_success", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlansListResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.RolloutPlansListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("project",)) + ) + + +def test_list_rest_flattened(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlansListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.RolloutPlansListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rolloutPlans" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list( + compute.ListRolloutPlansRequest(), + project="project_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + compute.RolloutPlansListResponse( + items=[ + compute.RolloutPlan(), + compute.RolloutPlan(), + compute.RolloutPlan(), + ], + next_page_token="abc", + ), + compute.RolloutPlansListResponse( + items=[], + next_page_token="def", + ), + compute.RolloutPlansListResponse( + items=[ + compute.RolloutPlan(), + ], + next_page_token="ghi", + ), + compute.RolloutPlansListResponse( + items=[ + compute.RolloutPlan(), + compute.RolloutPlan(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RolloutPlansListResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project": "sample1"} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.RolloutPlan) for i in results) + + pages = list(client.list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutPlansClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RolloutPlansClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RolloutPlansClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutPlansClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RolloutPlansClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RolloutPlansRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = RolloutPlansClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_delete_rest_bad_request(request_type=compute.DeleteRolloutPlanRequest): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout_plan": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRolloutPlanRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout_plan": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RolloutPlansRestInterceptor(), + ) + client = RolloutPlansClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.RolloutPlansRestInterceptor, "post_delete" + ) as post, + mock.patch.object( + transports.RolloutPlansRestInterceptor, "post_delete_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutPlansRestInterceptor, "pre_delete") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteRolloutPlanRequest.pb( + compute.DeleteRolloutPlanRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteRolloutPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rest_bad_request(request_type=compute.GetRolloutPlanRequest): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout_plan": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetRolloutPlanRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout_plan": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlan( + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + kind="kind_value", + location_scope="location_scope_value", + name="name_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.RolloutPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.RolloutPlan) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.location_scope == "location_scope_value" + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RolloutPlansRestInterceptor(), + ) + client = RolloutPlansClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RolloutPlansRestInterceptor, "post_get") as post, + mock.patch.object( + transports.RolloutPlansRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutPlansRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRolloutPlanRequest.pb(compute.GetRolloutPlanRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.RolloutPlan.to_json(compute.RolloutPlan()) + req.return_value.content = return_value + + request = compute.GetRolloutPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.RolloutPlan() + post_with_metadata.return_value = compute.RolloutPlan(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_insert_rest_bad_request(request_type=compute.InsertRolloutPlanRequest): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.insert(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertRolloutPlanRequest, + dict, + ], +) +def test_insert_rest_call_success(request_type): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request_init["rollout_plan_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "location_scope": "location_scope_value", + "name": "name_value", + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "waves": [ + { + "display_name": "display_name_value", + "number": 649, + "orchestration_options": { + "delays": [ + { + "delimiter": "delimiter_value", + "duration": "duration_value", + "type_": "type__value", + } + ], + "max_concurrent_locations": 2579, + "max_concurrent_resources_per_location": 3968, + }, + "selectors": [ + { + "location_selector": { + "included_locations": [ + "included_locations_value1", + "included_locations_value2", + ] + }, + "resource_hierarchy_selector": { + "included_folders": [ + "included_folders_value1", + "included_folders_value2", + ], + "included_organizations": [ + "included_organizations_value1", + "included_organizations_value2", + ], + "included_projects": [ + "included_projects_value1", + "included_projects_value2", + ], + }, + } + ], + "validation": { + "time_based_validation_metadata": { + "wait_duration": "wait_duration_value" + }, + "type_": "type__value", + }, + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.InsertRolloutPlanRequest.meta.fields["rollout_plan_resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "rollout_plan_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["rollout_plan_resource"][field])): + del request_init["rollout_plan_resource"][field][i][subfield] + else: + del request_init["rollout_plan_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.insert(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_rest_interceptors(null_interceptor): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RolloutPlansRestInterceptor(), + ) + client = RolloutPlansClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.RolloutPlansRestInterceptor, "post_insert" + ) as post, + mock.patch.object( + transports.RolloutPlansRestInterceptor, "post_insert_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutPlansRestInterceptor, "pre_insert") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.InsertRolloutPlanRequest.pb( + compute.InsertRolloutPlanRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.InsertRolloutPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.insert( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_rest_bad_request(request_type=compute.ListRolloutPlansRequest): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListRolloutPlansRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlansListResponse( + etag="etag_value", + id="id_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.RolloutPlansListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPager) + assert response.etag == "etag_value" + assert response.id == "id_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.RolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RolloutPlansRestInterceptor(), + ) + client = RolloutPlansClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RolloutPlansRestInterceptor, "post_list") as post, + mock.patch.object( + transports.RolloutPlansRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutPlansRestInterceptor, "pre_list") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListRolloutPlansRequest.pb( + compute.ListRolloutPlansRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.RolloutPlansListResponse.to_json( + compute.RolloutPlansListResponse() + ) + req.return_value.content = return_value + + request = compute.ListRolloutPlansRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.RolloutPlansListResponse() + post_with_metadata.return_value = compute.RolloutPlansListResponse(), metadata + + client.list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_unary_empty_call_rest(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete), "__call__") as call: + client.delete_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.DeleteRolloutPlanRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_empty_call_rest(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get), "__call__") as call: + client.get(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetRolloutPlanRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_insert_unary_empty_call_rest(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.insert), "__call__") as call: + client.insert_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.InsertRolloutPlanRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_empty_call_rest(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list), "__call__") as call: + client.list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ListRolloutPlansRequest() + + assert args[0] == request_msg + + +def test_rollout_plans_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RolloutPlansTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_rollout_plans_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.rollout_plans.transports.RolloutPlansTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RolloutPlansTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "delete", + "get", + "insert", + "list", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_rollout_plans_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.compute_v1.services.rollout_plans.transports.RolloutPlansTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RolloutPlansTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_rollout_plans_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.compute_v1.services.rollout_plans.transports.RolloutPlansTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RolloutPlansTransport() + adc.assert_called_once() + + +def test_rollout_plans_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RolloutPlansClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_rollout_plans_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.RolloutPlansRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_rollout_plans_host_no_port(transport_name): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_rollout_plans_host_with_port(transport_name): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_rollout_plans_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RolloutPlansClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RolloutPlansClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.delete._session + session2 = client2.transport.delete._session + assert session1 != session2 + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.insert._session + session2 = client2.transport.insert._session + assert session1 != session2 + session1 = client1.transport.list._session + session2 = client2.transport.list._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RolloutPlansClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RolloutPlansClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutPlansClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RolloutPlansClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RolloutPlansClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutPlansClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = RolloutPlansClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RolloutPlansClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutPlansClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RolloutPlansClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RolloutPlansClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutPlansClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = RolloutPlansClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RolloutPlansClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutPlansClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RolloutPlansTransport, "_prep_wrapped_messages" + ) as prep: + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RolloutPlansTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RolloutPlansClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = RolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (RolloutPlansClient, transports.RolloutPlansRestTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollouts.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollouts.py new file mode 100644 index 000000000000..fc21a7d57c9c --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollouts.py @@ -0,0 +1,3492 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.extended_operation as extended_operation # type: ignore +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1.services.rollouts import RolloutsClient, pagers, transports +from google.cloud.compute_v1.types import compute + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + custom_endpoint = ".custom" + + assert RolloutsClient._get_default_mtls_endpoint(None) is None + assert RolloutsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + RolloutsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RolloutsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RolloutsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert RolloutsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert RolloutsClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint + + +def test__read_environment_variables(): + assert RolloutsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RolloutsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RolloutsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + RolloutsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert RolloutsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RolloutsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RolloutsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RolloutsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RolloutsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert RolloutsClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert RolloutsClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert RolloutsClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RolloutsClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert RolloutsClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert RolloutsClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert RolloutsClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert RolloutsClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert RolloutsClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert RolloutsClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + RolloutsClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert RolloutsClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert RolloutsClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RolloutsClient._get_client_cert_source(None, False) is None + assert ( + RolloutsClient._get_client_cert_source(mock_provided_cert_source, False) is None + ) + assert ( + RolloutsClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + RolloutsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RolloutsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + RolloutsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RolloutsClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RolloutsClient._DEFAULT_UNIVERSE + default_endpoint = RolloutsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RolloutsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + RolloutsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RolloutsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RolloutsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RolloutsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + RolloutsClient._get_api_endpoint(None, None, default_universe, "always") + == RolloutsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RolloutsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RolloutsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RolloutsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + RolloutsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + RolloutsClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + RolloutsClient._get_universe_domain(client_universe_domain, universe_domain_env) + == client_universe_domain + ) + assert ( + RolloutsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RolloutsClient._get_universe_domain(None, None) + == RolloutsClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + RolloutsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = RolloutsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = RolloutsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RolloutsClient, "rest"), + ], +) +def test_rollouts_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.RolloutsRestTransport, "rest"), + ], +) +def test_rollouts_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RolloutsClient, "rest"), + ], +) +def test_rollouts_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_rollouts_client_get_transport_class(): + transport = RolloutsClient.get_transport_class() + available_transports = [ + transports.RolloutsRestTransport, + ] + assert transport in available_transports + + transport = RolloutsClient.get_transport_class("rest") + assert transport == transports.RolloutsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RolloutsClient, transports.RolloutsRestTransport, "rest"), + ], +) +@mock.patch.object( + RolloutsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RolloutsClient), +) +def test_rollouts_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RolloutsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RolloutsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (RolloutsClient, transports.RolloutsRestTransport, "rest", "true"), + (RolloutsClient, transports.RolloutsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + RolloutsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RolloutsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_rollouts_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [RolloutsClient]) +@mock.patch.object( + RolloutsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RolloutsClient) +) +def test_rollouts_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [RolloutsClient]) +@mock.patch.object( + RolloutsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RolloutsClient), +) +def test_rollouts_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RolloutsClient._DEFAULT_UNIVERSE + default_endpoint = RolloutsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RolloutsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RolloutsClient, transports.RolloutsRestTransport, "rest"), + ], +) +def test_rollouts_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (RolloutsClient, transports.RolloutsRestTransport, "rest", None), + ], +) +def test_rollouts_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_cancel_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.cancel in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.cancel] = mock_rpc + + request = {} + client.cancel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.cancel(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "rollback", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_cancel_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.cancel._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "rollback", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_cancel_rest_flattened(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.cancel(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_cancel_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.cancel( + compute.CancelRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_cancel_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.cancel in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.cancel] = mock_rpc + + request = {} + client.cancel_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.cancel_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "rollback", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_cancel_unary_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.cancel._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "rollback", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_cancel_unary_rest_flattened(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.cancel_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_cancel_unary_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.cancel_unary( + compute.CancelRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_delete_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete] = mock_rpc + + request = {} + client.delete(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_delete_rest_flattened(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete( + compute.DeleteRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_delete_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete] = mock_rpc + + request = {} + client.delete_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_delete_unary_rest_flattened(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_unary( + compute.DeleteRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_get_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get] = mock_rpc + + request = {} + client.get(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Rollout() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Rollout.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_get_rest_flattened(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Rollout() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Rollout.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get( + compute.GetRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_list_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list] = mock_rpc + + request = {} + client.list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "order_by", + "page_token", + "return_partial_success", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.RolloutsListResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.RolloutsListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("project",)) + ) + + +def test_list_rest_flattened(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RolloutsListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.RolloutsListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/global/rollouts" % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list( + compute.ListRolloutsRequest(), + project="project_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + compute.RolloutsListResponse( + items=[ + compute.Rollout(), + compute.Rollout(), + compute.Rollout(), + ], + next_page_token="abc", + ), + compute.RolloutsListResponse( + items=[], + next_page_token="def", + ), + compute.RolloutsListResponse( + items=[ + compute.Rollout(), + ], + next_page_token="ghi", + ), + compute.RolloutsListResponse( + items=[ + compute.Rollout(), + compute.Rollout(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RolloutsListResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project": "sample1"} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.Rollout) for i in results) + + pages = list(client.list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RolloutsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RolloutsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RolloutsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RolloutsRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = RolloutsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_cancel_rest_bad_request(request_type=compute.CancelRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CancelRolloutRequest, + dict, + ], +) +def test_cancel_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.cancel(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RolloutsRestInterceptor, "post_cancel") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_cancel_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_cancel") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CancelRolloutRequest.pb(compute.CancelRolloutRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.CancelRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.cancel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_rest_bad_request(request_type=compute.DeleteRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRolloutRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RolloutsRestInterceptor, "post_delete") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_delete_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_delete") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteRolloutRequest.pb(compute.DeleteRolloutRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rest_bad_request(request_type=compute.GetRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetRolloutRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Rollout( + cancellation_time="cancellation_time_value", + completion_time="completion_time_value", + creation_timestamp="creation_timestamp_value", + current_wave_number=2045, + description="description_value", + etag="etag_value", + id=205, + kind="kind_value", + name="name_value", + rollout_plan="rollout_plan_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + state="state_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Rollout.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Rollout) + assert response.cancellation_time == "cancellation_time_value" + assert response.completion_time == "completion_time_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.current_wave_number == 2045 + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.rollout_plan == "rollout_plan_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.state == "state_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RolloutsRestInterceptor, "post_get") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRolloutRequest.pb(compute.GetRolloutRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Rollout.to_json(compute.Rollout()) + req.return_value.content = return_value + + request = compute.GetRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Rollout() + post_with_metadata.return_value = compute.Rollout(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_rest_bad_request(request_type=compute.ListRolloutsRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListRolloutsRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RolloutsListResponse( + etag="etag_value", + id="id_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.RolloutsListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPager) + assert response.etag == "etag_value" + assert response.id == "id_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RolloutsRestInterceptor, "post_list") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_list") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListRolloutsRequest.pb(compute.ListRolloutsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.RolloutsListResponse.to_json( + compute.RolloutsListResponse() + ) + req.return_value.content = return_value + + request = compute.ListRolloutsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.RolloutsListResponse() + post_with_metadata.return_value = compute.RolloutsListResponse(), metadata + + client.list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_cancel_unary_empty_call_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.cancel), "__call__") as call: + client.cancel_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CancelRolloutRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_unary_empty_call_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete), "__call__") as call: + client.delete_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.DeleteRolloutRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_empty_call_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get), "__call__") as call: + client.get(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetRolloutRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_empty_call_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list), "__call__") as call: + client.list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ListRolloutsRequest() + + assert args[0] == request_msg + + +def test_rollouts_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RolloutsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_rollouts_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.rollouts.transports.RolloutsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RolloutsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "cancel", + "delete", + "get", + "list", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_rollouts_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.compute_v1.services.rollouts.transports.RolloutsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RolloutsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_rollouts_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.compute_v1.services.rollouts.transports.RolloutsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RolloutsTransport() + adc.assert_called_once() + + +def test_rollouts_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RolloutsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_rollouts_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.RolloutsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_rollouts_host_no_port(transport_name): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_rollouts_host_with_port(transport_name): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_rollouts_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RolloutsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RolloutsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.cancel._session + session2 = client2.transport.cancel._session + assert session1 != session2 + session1 = client1.transport.delete._session + session2 = client2.transport.delete._session + assert session1 != session2 + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.list._session + session2 = client2.transport.list._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RolloutsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RolloutsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RolloutsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RolloutsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = RolloutsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RolloutsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RolloutsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RolloutsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = RolloutsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RolloutsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RolloutsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RolloutsTransport, "_prep_wrapped_messages" + ) as prep: + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RolloutsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RolloutsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (RolloutsClient, transports.RolloutsRestTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py index 22b7fe40169a..4e49142e3985 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py @@ -3687,6 +3687,7 @@ def test_get_rest_call_success(request_type): kind="kind_value", min_tls_version="min_tls_version_value", name="name_value", + post_quantum_key_exchange="post_quantum_key_exchange_value", profile="profile_value", region="region_value", self_link="self_link_value", @@ -3715,6 +3716,7 @@ def test_get_rest_call_success(request_type): assert response.kind == "kind_value" assert response.min_tls_version == "min_tls_version_value" assert response.name == "name_value" + assert response.post_quantum_key_exchange == "post_quantum_key_exchange_value" assert response.profile == "profile_value" assert response.region == "region_value" assert response.self_link == "self_link_value" @@ -3826,6 +3828,7 @@ def test_insert_rest_call_success(request_type): "kind": "kind_value", "min_tls_version": "min_tls_version_value", "name": "name_value", + "post_quantum_key_exchange": "post_quantum_key_exchange_value", "profile": "profile_value", "region": "region_value", "self_link": "self_link_value", @@ -4342,6 +4345,7 @@ def test_patch_rest_call_success(request_type): "kind": "kind_value", "min_tls_version": "min_tls_version_value", "name": "name_value", + "post_quantum_key_exchange": "post_quantum_key_exchange_value", "profile": "profile_value", "region": "region_value", "self_link": "self_link_value", diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter/__init__.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter/__init__.py index babe94c01521..a792a9323d24 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter/__init__.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter/__init__.py @@ -54,6 +54,8 @@ AggregateFleetRow, AggregateIssueStatsRequest, AggregateIssueStatsResponse, + AggregateQueryStatsRequest, + AggregateQueryStatsResponse, BackupDRConfig, DatabaseResource, DatabaseResourceGroup, @@ -69,10 +71,14 @@ QueryDatabaseResourceGroupsResponse, QueryIssuesRequest, QueryIssuesResponse, + QueryMetrics, QueryProductsRequest, QueryProductsResponse, + QueryStats, + QueryStatsInfo, ResourceCategory, ResourceDetails, + ResourceId, SignalProductsFilters, SubResourceType, Tag, @@ -127,6 +133,8 @@ "AggregateFleetRow", "AggregateIssueStatsRequest", "AggregateIssueStatsResponse", + "AggregateQueryStatsRequest", + "AggregateQueryStatsResponse", "BackupDRConfig", "DatabaseResource", "DatabaseResourceGroup", @@ -140,9 +148,13 @@ "QueryDatabaseResourceGroupsResponse", "QueryIssuesRequest", "QueryIssuesResponse", + "QueryMetrics", "QueryProductsRequest", "QueryProductsResponse", + "QueryStats", + "QueryStatsInfo", "ResourceDetails", + "ResourceId", "SignalProductsFilters", "Tag", "Edition", diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/__init__.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/__init__.py index 72411775ecc9..85d7aa68fe13 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/__init__.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/__init__.py @@ -44,6 +44,8 @@ AggregateFleetRow, AggregateIssueStatsRequest, AggregateIssueStatsResponse, + AggregateQueryStatsRequest, + AggregateQueryStatsResponse, BackupDRConfig, DatabaseResource, DatabaseResourceGroup, @@ -59,10 +61,14 @@ QueryDatabaseResourceGroupsResponse, QueryIssuesRequest, QueryIssuesResponse, + QueryMetrics, QueryProductsRequest, QueryProductsResponse, + QueryStats, + QueryStatsInfo, ResourceCategory, ResourceDetails, + ResourceId, SignalProductsFilters, SubResourceType, Tag, @@ -185,6 +191,8 @@ def _get_version(dependency_name): "AggregateFleetRow", "AggregateIssueStatsRequest", "AggregateIssueStatsResponse", + "AggregateQueryStatsRequest", + "AggregateQueryStatsResponse", "AutomatedBackupPolicyInfo", "BackupDRConfig", "BackupRunInfo", @@ -220,12 +228,16 @@ def _get_version(dependency_name): "QueryDatabaseResourceGroupsResponse", "QueryIssuesRequest", "QueryIssuesResponse", + "QueryMetrics", "QueryProductsRequest", "QueryProductsResponse", + "QueryStats", + "QueryStatsInfo", "RecommendationInfo", "RegulatoryStandard", "ResourceCategory", "ResourceDetails", + "ResourceId", "ResourceMaintenanceDenySchedule", "ResourceMaintenanceSchedule", "ResourceSuspensionInfo", diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/gapic_metadata.json b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/gapic_metadata.json index 682c4b833ff8..75145e864e26 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/gapic_metadata.json +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/gapic_metadata.json @@ -20,6 +20,11 @@ "aggregate_issue_stats" ] }, + "AggregateQueryStats": { + "methods": [ + "aggregate_query_stats" + ] + }, "QueryDatabaseResourceGroups": { "methods": [ "query_database_resource_groups" @@ -50,6 +55,11 @@ "aggregate_issue_stats" ] }, + "AggregateQueryStats": { + "methods": [ + "aggregate_query_stats" + ] + }, "QueryDatabaseResourceGroups": { "methods": [ "query_database_resource_groups" @@ -80,6 +90,11 @@ "aggregate_issue_stats" ] }, + "AggregateQueryStats": { + "methods": [ + "aggregate_query_stats" + ] + }, "QueryDatabaseResourceGroups": { "methods": [ "query_database_resource_groups" diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/async_client.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/async_client.py index fd232433c765..fde5e7ae82be 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/async_client.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/async_client.py @@ -670,6 +670,111 @@ async def sample_aggregate_issue_stats(): # Done; return the response. return response + async def aggregate_query_stats( + self, + request: Optional[Union[service.AggregateQueryStatsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AggregateQueryStatsAsyncPager: + r"""AggregateQueryStats provides database resource query + execution statistics. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import databasecenter_v1beta + + async def sample_aggregate_query_stats(): + # Create a client + client = databasecenter_v1beta.DatabaseCenterAsyncClient() + + # Initialize request argument(s) + request = databasecenter_v1beta.AggregateQueryStatsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.aggregate_query_stats(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.databasecenter_v1beta.types.AggregateQueryStatsRequest, dict]]): + The request object. AggregateQueryStatsRequest represents + the input to the AggregateQueryStats + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.databasecenter_v1beta.services.database_center.pagers.AggregateQueryStatsAsyncPager: + The response message containing + relevant query stats for database + resources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.AggregateQueryStatsRequest): + request = service.AggregateQueryStatsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.aggregate_query_stats + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.AggregateQueryStatsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def query_issues( self, request: Optional[Union[service.QueryIssuesRequest, dict]] = None, diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/client.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/client.py index 2d56e620c25f..54afbd03c5c4 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/client.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/client.py @@ -1078,6 +1078,109 @@ def sample_aggregate_issue_stats(): # Done; return the response. return response + def aggregate_query_stats( + self, + request: Optional[Union[service.AggregateQueryStatsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.AggregateQueryStatsPager: + r"""AggregateQueryStats provides database resource query + execution statistics. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import databasecenter_v1beta + + def sample_aggregate_query_stats(): + # Create a client + client = databasecenter_v1beta.DatabaseCenterClient() + + # Initialize request argument(s) + request = databasecenter_v1beta.AggregateQueryStatsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.aggregate_query_stats(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.databasecenter_v1beta.types.AggregateQueryStatsRequest, dict]): + The request object. AggregateQueryStatsRequest represents + the input to the AggregateQueryStats + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.databasecenter_v1beta.services.database_center.pagers.AggregateQueryStatsPager: + The response message containing + relevant query stats for database + resources. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.AggregateQueryStatsRequest): + request = service.AggregateQueryStatsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.aggregate_query_stats] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.AggregateQueryStatsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def query_issues( self, request: Optional[Union[service.QueryIssuesRequest, dict]] = None, diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/pagers.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/pagers.py index b30d8838cc85..0fdb25055939 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/pagers.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/pagers.py @@ -509,6 +509,162 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class AggregateQueryStatsPager: + """A pager for iterating through ``aggregate_query_stats`` requests. + + This class thinly wraps an initial + :class:`google.cloud.databasecenter_v1beta.types.AggregateQueryStatsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``query_stats`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``AggregateQueryStats`` requests and continue to iterate + through the ``query_stats`` field on the + corresponding responses. + + All the usual :class:`google.cloud.databasecenter_v1beta.types.AggregateQueryStatsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.AggregateQueryStatsResponse], + request: service.AggregateQueryStatsRequest, + response: service.AggregateQueryStatsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.databasecenter_v1beta.types.AggregateQueryStatsRequest): + The initial request object. + response (google.cloud.databasecenter_v1beta.types.AggregateQueryStatsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.AggregateQueryStatsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.AggregateQueryStatsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[service.QueryStatsInfo]: + for page in self.pages: + yield from page.query_stats + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class AggregateQueryStatsAsyncPager: + """A pager for iterating through ``aggregate_query_stats`` requests. + + This class thinly wraps an initial + :class:`google.cloud.databasecenter_v1beta.types.AggregateQueryStatsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``query_stats`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``AggregateQueryStats`` requests and continue to iterate + through the ``query_stats`` field on the + corresponding responses. + + All the usual :class:`google.cloud.databasecenter_v1beta.types.AggregateQueryStatsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.AggregateQueryStatsResponse]], + request: service.AggregateQueryStatsRequest, + response: service.AggregateQueryStatsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.databasecenter_v1beta.types.AggregateQueryStatsRequest): + The initial request object. + response (google.cloud.databasecenter_v1beta.types.AggregateQueryStatsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.AggregateQueryStatsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.AggregateQueryStatsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[service.QueryStatsInfo]: + async def async_generator(): + async for page in self.pages: + for response in page.query_stats: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class QueryIssuesPager: """A pager for iterating through ``query_issues`` requests. diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/base.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/base.py index b923f75368cb..ee2ee9e67dca 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/base.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/base.py @@ -162,6 +162,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.aggregate_query_stats: gapic_v1.method.wrap_method( + self.aggregate_query_stats, + default_timeout=None, + client_info=client_info, + ), self.query_issues: gapic_v1.method.wrap_method( self.query_issues, default_timeout=None, @@ -222,6 +227,18 @@ def aggregate_issue_stats( ]: raise NotImplementedError() + @property + def aggregate_query_stats( + self, + ) -> Callable[ + [service.AggregateQueryStatsRequest], + Union[ + service.AggregateQueryStatsResponse, + Awaitable[service.AggregateQueryStatsResponse], + ], + ]: + raise NotImplementedError() + @property def query_issues( self, diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc.py index 78549b06d43a..1b6281f26525 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc.py @@ -441,6 +441,35 @@ def aggregate_issue_stats( ) return self._stubs["aggregate_issue_stats"] + @property + def aggregate_query_stats( + self, + ) -> Callable[ + [service.AggregateQueryStatsRequest], service.AggregateQueryStatsResponse + ]: + r"""Return a callable for the aggregate query stats method over gRPC. + + AggregateQueryStats provides database resource query + execution statistics. + + Returns: + Callable[[~.AggregateQueryStatsRequest], + ~.AggregateQueryStatsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "aggregate_query_stats" not in self._stubs: + self._stubs["aggregate_query_stats"] = self._logged_channel.unary_unary( + "/google.cloud.databasecenter.v1beta.DatabaseCenter/AggregateQueryStats", + request_serializer=service.AggregateQueryStatsRequest.serialize, + response_deserializer=service.AggregateQueryStatsResponse.deserialize, + ) + return self._stubs["aggregate_query_stats"] + @property def query_issues( self, diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc_asyncio.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc_asyncio.py index c4b8c8d422a8..26c018d14a65 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc_asyncio.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/grpc_asyncio.py @@ -454,6 +454,36 @@ def aggregate_issue_stats( ) return self._stubs["aggregate_issue_stats"] + @property + def aggregate_query_stats( + self, + ) -> Callable[ + [service.AggregateQueryStatsRequest], + Awaitable[service.AggregateQueryStatsResponse], + ]: + r"""Return a callable for the aggregate query stats method over gRPC. + + AggregateQueryStats provides database resource query + execution statistics. + + Returns: + Callable[[~.AggregateQueryStatsRequest], + Awaitable[~.AggregateQueryStatsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "aggregate_query_stats" not in self._stubs: + self._stubs["aggregate_query_stats"] = self._logged_channel.unary_unary( + "/google.cloud.databasecenter.v1beta.DatabaseCenter/AggregateQueryStats", + request_serializer=service.AggregateQueryStatsRequest.serialize, + response_deserializer=service.AggregateQueryStatsResponse.deserialize, + ) + return self._stubs["aggregate_query_stats"] + @property def query_issues( self, @@ -505,6 +535,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.aggregate_query_stats: self._wrap_method( + self.aggregate_query_stats, + default_timeout=None, + client_info=client_info, + ), self.query_issues: self._wrap_method( self.query_issues, default_timeout=None, diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest.py index 3c25ea7c7a4d..5af5e81bc267 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest.py @@ -88,6 +88,14 @@ def post_aggregate_issue_stats(self, response): logging.log(f"Received response: {response}") return response + def pre_aggregate_query_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_aggregate_query_stats(self, response): + logging.log(f"Received response: {response}") + return response + def pre_query_database_resource_groups(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -214,6 +222,56 @@ def post_aggregate_issue_stats_with_metadata( """ return response, metadata + def pre_aggregate_query_stats( + self, + request: service.AggregateQueryStatsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.AggregateQueryStatsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for aggregate_query_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the DatabaseCenter server. + """ + return request, metadata + + def post_aggregate_query_stats( + self, response: service.AggregateQueryStatsResponse + ) -> service.AggregateQueryStatsResponse: + """Post-rpc interceptor for aggregate_query_stats + + DEPRECATED. Please use the `post_aggregate_query_stats_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DatabaseCenter server but before + it is returned to user code. This `post_aggregate_query_stats` interceptor runs + before the `post_aggregate_query_stats_with_metadata` interceptor. + """ + return response + + def post_aggregate_query_stats_with_metadata( + self, + response: service.AggregateQueryStatsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.AggregateQueryStatsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for aggregate_query_stats + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DatabaseCenter server but before it is returned to user code. + + We recommend only using this `post_aggregate_query_stats_with_metadata` + interceptor in new development instead of the `post_aggregate_query_stats` interceptor. + When both interceptors are used, this `post_aggregate_query_stats_with_metadata` interceptor runs after the + `post_aggregate_query_stats` interceptor. The (possibly modified) response returned by + `post_aggregate_query_stats` will be passed to + `post_aggregate_query_stats_with_metadata`. + """ + return response, metadata + def pre_query_database_resource_groups( self, request: service.QueryDatabaseResourceGroupsRequest, @@ -758,6 +816,164 @@ def __call__( ) return resp + class _AggregateQueryStats( + _BaseDatabaseCenterRestTransport._BaseAggregateQueryStats, + DatabaseCenterRestStub, + ): + def __hash__(self): + return hash("DatabaseCenterRestTransport.AggregateQueryStats") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.AggregateQueryStatsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.AggregateQueryStatsResponse: + r"""Call the aggregate query stats method over HTTP. + + Args: + request (~.service.AggregateQueryStatsRequest): + The request object. AggregateQueryStatsRequest represents + the input to the AggregateQueryStats + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.AggregateQueryStatsResponse: + The response message containing + relevant query stats for database + resources. + + """ + + http_options = _BaseDatabaseCenterRestTransport._BaseAggregateQueryStats._get_http_options() + + request, metadata = self._interceptor.pre_aggregate_query_stats( + request, metadata + ) + transcoded_request = _BaseDatabaseCenterRestTransport._BaseAggregateQueryStats._get_transcoded_request( + http_options, request + ) + + body = _BaseDatabaseCenterRestTransport._BaseAggregateQueryStats._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseDatabaseCenterRestTransport._BaseAggregateQueryStats._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.databasecenter_v1beta.DatabaseCenterClient.AggregateQueryStats", + extra={ + "serviceName": "google.cloud.databasecenter.v1beta.DatabaseCenter", + "rpcName": "AggregateQueryStats", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DatabaseCenterRestTransport._AggregateQueryStats._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.AggregateQueryStatsResponse() + pb_resp = service.AggregateQueryStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_aggregate_query_stats(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_aggregate_query_stats_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.AggregateQueryStatsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.databasecenter_v1beta.DatabaseCenterClient.aggregate_query_stats", + extra={ + "serviceName": "google.cloud.databasecenter.v1beta.DatabaseCenter", + "rpcName": "AggregateQueryStats", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _QueryDatabaseResourceGroups( _BaseDatabaseCenterRestTransport._BaseQueryDatabaseResourceGroups, DatabaseCenterRestStub, @@ -1239,6 +1455,16 @@ def aggregate_issue_stats( # In C++ this would require a dynamic_cast return self._AggregateIssueStats(self._session, self._host, self._interceptor) # type: ignore + @property + def aggregate_query_stats( + self, + ) -> Callable[ + [service.AggregateQueryStatsRequest], service.AggregateQueryStatsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AggregateQueryStats(self._session, self._host, self._interceptor) # type: ignore + @property def query_database_resource_groups( self, diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest_base.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest_base.py index ecb543e3241c..04d8d462ed39 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest_base.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/services/database_center/transports/rest_base.py @@ -193,6 +193,73 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseAggregateQueryStats: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=organizations/*}:aggregateQueryStats", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{parent=folders/*}:aggregateQueryStats", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*}:aggregateQueryStats", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.AggregateQueryStatsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseDatabaseCenterRestTransport._BaseAggregateQueryStats._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseQueryDatabaseResourceGroups: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/__init__.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/__init__.py index 57cb47be7454..7a69ceec03c9 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/__init__.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/__init__.py @@ -47,6 +47,8 @@ AggregateFleetRow, AggregateIssueStatsRequest, AggregateIssueStatsResponse, + AggregateQueryStatsRequest, + AggregateQueryStatsResponse, BackupDRConfig, DatabaseResource, DatabaseResourceGroup, @@ -62,10 +64,14 @@ QueryDatabaseResourceGroupsResponse, QueryIssuesRequest, QueryIssuesResponse, + QueryMetrics, QueryProductsRequest, QueryProductsResponse, + QueryStats, + QueryStatsInfo, ResourceCategory, ResourceDetails, + ResourceId, SignalProductsFilters, SubResourceType, Tag, @@ -120,6 +126,8 @@ "AggregateFleetRow", "AggregateIssueStatsRequest", "AggregateIssueStatsResponse", + "AggregateQueryStatsRequest", + "AggregateQueryStatsResponse", "BackupDRConfig", "DatabaseResource", "DatabaseResourceGroup", @@ -133,9 +141,13 @@ "QueryDatabaseResourceGroupsResponse", "QueryIssuesRequest", "QueryIssuesResponse", + "QueryMetrics", "QueryProductsRequest", "QueryProductsResponse", + "QueryStats", + "QueryStatsInfo", "ResourceDetails", + "ResourceId", "SignalProductsFilters", "Tag", "Edition", diff --git a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/service.py b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/service.py index a0e6d02bf076..1c6db5515d3b 100644 --- a/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/service.py +++ b/packages/google-cloud-databasecenter/google/cloud/databasecenter_v1beta/types/service.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.type.date_pb2 as date_pb2 # type: ignore import proto # type: ignore @@ -45,11 +46,17 @@ "DatabaseResourceGroup", "DatabaseResource", "AggregateIssueStatsRequest", + "AggregateQueryStatsRequest", + "AggregateQueryStatsResponse", "AggregateIssueStatsResponse", "IssueGroupStats", "IssueStats", "Label", "AggregateFleetRequest", + "QueryStatsInfo", + "ResourceId", + "QueryStats", + "QueryMetrics", "AggregateFleetResponse", "AggregateFleetRow", "Dimension", @@ -709,6 +716,126 @@ class AggregateIssueStatsRequest(proto.Message): ) +class AggregateQueryStatsRequest(proto.Message): + r"""AggregateQueryStatsRequest represents the input to the + AggregateQueryStats method. + + Attributes: + parent (str): + Required. Parent can be a project, a folder, or an + organization. The search is limited to the resources within + the ``parent``. + + The allowed values are: + + - projects/{PROJECT_ID} (e.g., "projects/foo-bar") + - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") + - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + order_by (str): + Optional. The expression to order the results by. Example: + ``order_by="execution_count"`` Example: + ``order_by="execution_count desc"`` Supported order by + fields are ``execution_count``, ``rows_processed``, + ``total_cpu_time``, ``avg_cpu_time``. + filter (str): + Optional. The expression to filter resources. + + Supported fields are: ``full_resource_name``, + ``resource_type``, ``container``, ``product.type``, + ``product.engine``, ``product.version``, ``location``, + ``labels``, ``issues``, fields of availability_info, + data_protection_info,'resource_name', etc. + + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. When + ``AND`` and ``OR`` are both used in the expression, + parentheses must be appropriately used to group the + combinations. + + Example: ``location="us-east1"`` Example: + ``container="projects/123" OR container="projects/456"`` + Example: + ``(container="projects/123" OR container="projects/456") AND location="us-east1"`` + Additional specific fields for query stats are: + ``metric_window``, ``query_hash``, ``normalized_query``. + Example: ``metric_window="LAST_ONE_DAY"`` (Possible values + for ``metric_window`` are: ``LAST_ONE_DAY``, + ``LAST_ONE_WEEK``, ``LAST_TWO_WEEKS``) Example: + ``query_hash="12345678"`` Example: + ``normalized_query="SELECT * FROM table"`` + page_size (int): + Optional. If unspecified, at most 100 query + stats will be returned. The maximum value is + 1000; values above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``AggregateQueryStatsRequest`` call. Provide this to + retrieve the subsequent page. All parameters except + page_token should match the parameters in the call that + provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + order_by: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class AggregateQueryStatsResponse(proto.Message): + r"""The response message containing relevant query stats + for database resources. + + Attributes: + query_stats (MutableSequence[google.cloud.databasecenter_v1beta.types.QueryStatsInfo]): + List of query stats where each group contains + stats for resources having a particular + combination of relevant query stats. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Unordered list. List of unreachable regions + from where data could not be retrieved. + """ + + @property + def raw_page(self): + return self + + query_stats: MutableSequence["QueryStatsInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="QueryStatsInfo", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class AggregateIssueStatsResponse(proto.Message): r"""The response message containing one of more group of relevant health issues for database resources. @@ -1007,6 +1134,184 @@ class AggregateFleetRequest(proto.Message): ) +class QueryStatsInfo(proto.Message): + r"""QueryStatsInfo contains the aggregated and detailed query + stats for a particular combination of relevant query stats for + queries having same normalized query. + + Attributes: + aggregated_query_stats (google.cloud.databasecenter_v1beta.types.QueryStats): + Aggregated query stats for the resources for + same normalized query. + query_stats (MutableSequence[google.cloud.databasecenter_v1beta.types.QueryStats]): + List of query stats for the resources in the + group. This stats is stats at resource level for + the resources having same normalized query. + """ + + aggregated_query_stats: "QueryStats" = proto.Field( + proto.MESSAGE, + number=1, + message="QueryStats", + ) + query_stats: MutableSequence["QueryStats"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="QueryStats", + ) + + +class ResourceId(proto.Message): + r"""ResourceId contains the identifier for a database resource, + including the full resource name, resource type, and product. + + Attributes: + full_resource_name (str): + The full resource name of the resource. + resource_type (str): + The type of the resource. + sqladmin.googleapis.com/Instance + alloydb.googleapis.com/Cluster + alloydb.googleapis.com/Instance + product (google.cloud.databasecenter_v1beta.types.Product): + The product of the resource, including the + type, engine, and version. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + product: gcd_product.Product = proto.Field( + proto.MESSAGE, + number=3, + message=gcd_product.Product, + ) + + +class QueryStats(proto.Message): + r"""QueryStats contains the stats for a particular combination of + query_hash, query_string and resource_type. + + Attributes: + query_hash (str): + The query hash of the query. + normalized_query (str): + The query string is normalized query without + any PII data. + resource_type (str): + The type of the resource. + sqladmin.googleapis.com/Instance + alloydb.googleapis.com/Cluster + alloydb.googleapis.com/Instance + resource_ids (MutableSequence[google.cloud.databasecenter_v1beta.types.ResourceId]): + The resource ids for which the query stats + are collected. + query_metrics (google.cloud.databasecenter_v1beta.types.QueryMetrics): + Metrics related to the query performance. + inefficient_query_info (google.cloud.databasecenter_v1beta.types.InefficientQueryInfo): + Information about inefficient query. + """ + + query_hash: str = proto.Field( + proto.STRING, + number=1, + ) + normalized_query: str = proto.Field( + proto.STRING, + number=2, + ) + resource_type: str = proto.Field( + proto.STRING, + number=4, + ) + resource_ids: MutableSequence["ResourceId"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="ResourceId", + ) + query_metrics: "QueryMetrics" = proto.Field( + proto.MESSAGE, + number=6, + message="QueryMetrics", + ) + inefficient_query_info: signals.InefficientQueryInfo = proto.Field( + proto.MESSAGE, + number=7, + message=signals.InefficientQueryInfo, + ) + + +class QueryMetrics(proto.Message): + r"""QueryMetrics contains the metrics related to the query + execution. + + Attributes: + execution_count (int): + The number of times the query was executed. + avg_cpu_time (google.protobuf.duration_pb2.Duration): + The average execution period of the query + across all runs. + total_cpu_time (google.protobuf.duration_pb2.Duration): + The total CPU time consumed by the query + across all runs. + rows_processed (int): + The average number of rows processed by the + query across all runs. + metrics_window (google.cloud.databasecenter_v1beta.types.QueryMetrics.MetricsWindow): + The window over which the metrics are + aggregated. + """ + + class MetricsWindow(proto.Enum): + r"""Enum to represent the window over which the metrics are + aggregated. + + Values: + METRICS_WINDOW_UNSPECIFIED (0): + Unspecified. Default value. + LAST_ONE_DAY (1): + Metrics are aggregated over the last 1 day. + LAST_ONE_WEEK (2): + Metrics are aggregated over the last 7 days. + LAST_TWO_WEEKS (3): + Metrics are aggregated over the last 14 days. + """ + + METRICS_WINDOW_UNSPECIFIED = 0 + LAST_ONE_DAY = 1 + LAST_ONE_WEEK = 2 + LAST_TWO_WEEKS = 3 + + execution_count: int = proto.Field( + proto.INT64, + number=1, + ) + avg_cpu_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + total_cpu_time: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + rows_processed: int = proto.Field( + proto.INT64, + number=4, + ) + metrics_window: MetricsWindow = proto.Field( + proto.ENUM, + number=5, + enum=MetricsWindow, + ) + + class AggregateFleetResponse(proto.Message): r"""The response message to aggregate a fleet by some group by fields. diff --git a/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_query_stats_async.py b/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_query_stats_async.py new file mode 100644 index 000000000000..50ef305f0571 --- /dev/null +++ b/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_query_stats_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AggregateQueryStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-databasecenter + + +# [START databasecenter_v1beta_generated_DatabaseCenter_AggregateQueryStats_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import databasecenter_v1beta + + +async def sample_aggregate_query_stats(): + # Create a client + client = databasecenter_v1beta.DatabaseCenterAsyncClient() + + # Initialize request argument(s) + request = databasecenter_v1beta.AggregateQueryStatsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.aggregate_query_stats(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END databasecenter_v1beta_generated_DatabaseCenter_AggregateQueryStats_async] diff --git a/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_query_stats_sync.py b/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_query_stats_sync.py new file mode 100644 index 000000000000..2b60fb0c162e --- /dev/null +++ b/packages/google-cloud-databasecenter/samples/generated_samples/databasecenter_v1beta_generated_database_center_aggregate_query_stats_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AggregateQueryStats +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-databasecenter + + +# [START databasecenter_v1beta_generated_DatabaseCenter_AggregateQueryStats_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import databasecenter_v1beta + + +def sample_aggregate_query_stats(): + # Create a client + client = databasecenter_v1beta.DatabaseCenterClient() + + # Initialize request argument(s) + request = databasecenter_v1beta.AggregateQueryStatsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.aggregate_query_stats(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END databasecenter_v1beta_generated_DatabaseCenter_AggregateQueryStats_sync] diff --git a/packages/google-cloud-databasecenter/samples/generated_samples/snippet_metadata_google.cloud.databasecenter.v1beta.json b/packages/google-cloud-databasecenter/samples/generated_samples/snippet_metadata_google.cloud.databasecenter.v1beta.json index fd836d744f28..3a9a71cab5ab 100644 --- a/packages/google-cloud-databasecenter/samples/generated_samples/snippet_metadata_google.cloud.databasecenter.v1beta.json +++ b/packages/google-cloud-databasecenter/samples/generated_samples/snippet_metadata_google.cloud.databasecenter.v1beta.json @@ -317,6 +317,159 @@ ], "title": "databasecenter_v1beta_generated_database_center_aggregate_issue_stats_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.databasecenter_v1beta.DatabaseCenterAsyncClient", + "shortName": "DatabaseCenterAsyncClient" + }, + "fullName": "google.cloud.databasecenter_v1beta.DatabaseCenterAsyncClient.aggregate_query_stats", + "method": { + "fullName": "google.cloud.databasecenter.v1beta.DatabaseCenter.AggregateQueryStats", + "service": { + "fullName": "google.cloud.databasecenter.v1beta.DatabaseCenter", + "shortName": "DatabaseCenter" + }, + "shortName": "AggregateQueryStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.databasecenter_v1beta.types.AggregateQueryStatsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.databasecenter_v1beta.services.database_center.pagers.AggregateQueryStatsAsyncPager", + "shortName": "aggregate_query_stats" + }, + "description": "Sample for AggregateQueryStats", + "file": "databasecenter_v1beta_generated_database_center_aggregate_query_stats_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "databasecenter_v1beta_generated_DatabaseCenter_AggregateQueryStats_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "databasecenter_v1beta_generated_database_center_aggregate_query_stats_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.databasecenter_v1beta.DatabaseCenterClient", + "shortName": "DatabaseCenterClient" + }, + "fullName": "google.cloud.databasecenter_v1beta.DatabaseCenterClient.aggregate_query_stats", + "method": { + "fullName": "google.cloud.databasecenter.v1beta.DatabaseCenter.AggregateQueryStats", + "service": { + "fullName": "google.cloud.databasecenter.v1beta.DatabaseCenter", + "shortName": "DatabaseCenter" + }, + "shortName": "AggregateQueryStats" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.databasecenter_v1beta.types.AggregateQueryStatsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.databasecenter_v1beta.services.database_center.pagers.AggregateQueryStatsPager", + "shortName": "aggregate_query_stats" + }, + "description": "Sample for AggregateQueryStats", + "file": "databasecenter_v1beta_generated_database_center_aggregate_query_stats_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "databasecenter_v1beta_generated_DatabaseCenter_AggregateQueryStats_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "databasecenter_v1beta_generated_database_center_aggregate_query_stats_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-databasecenter/tests/unit/gapic/databasecenter_v1beta/test_database_center.py b/packages/google-cloud-databasecenter/tests/unit/gapic/databasecenter_v1beta/test_database_center.py index cc404abf0277..dea5279f0212 100644 --- a/packages/google-cloud-databasecenter/tests/unit/gapic/databasecenter_v1beta/test_database_center.py +++ b/packages/google-cloud-databasecenter/tests/unit/gapic/databasecenter_v1beta/test_database_center.py @@ -2670,6 +2670,470 @@ async def test_aggregate_issue_stats_async_from_dict(): await test_aggregate_issue_stats_async(request_type=dict) +@pytest.mark.parametrize( + "request_type", + [ + service.AggregateQueryStatsRequest, + dict, + ], +) +def test_aggregate_query_stats(request_type, transport: str = "grpc"): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.AggregateQueryStatsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.aggregate_query_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.AggregateQueryStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AggregateQueryStatsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_aggregate_query_stats_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.AggregateQueryStatsRequest( + parent="parent_value", + order_by="order_by_value", + filter="filter_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.aggregate_query_stats(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.AggregateQueryStatsRequest( + parent="parent_value", + order_by="order_by_value", + filter="filter_value", + page_token="page_token_value", + ) + + +def test_aggregate_query_stats_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.aggregate_query_stats + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.aggregate_query_stats] = ( + mock_rpc + ) + request = {} + client.aggregate_query_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.aggregate_query_stats(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_aggregate_query_stats_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.aggregate_query_stats + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.aggregate_query_stats + ] = mock_rpc + + request = {} + await client.aggregate_query_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.aggregate_query_stats(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_aggregate_query_stats_async( + transport: str = "grpc_asyncio", request_type=service.AggregateQueryStatsRequest +): + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AggregateQueryStatsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.aggregate_query_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.AggregateQueryStatsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AggregateQueryStatsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_aggregate_query_stats_async_from_dict(): + await test_aggregate_query_stats_async(request_type=dict) + + +def test_aggregate_query_stats_field_headers(): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AggregateQueryStatsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + call.return_value = service.AggregateQueryStatsResponse() + client.aggregate_query_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_aggregate_query_stats_field_headers_async(): + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AggregateQueryStatsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AggregateQueryStatsResponse() + ) + await client.aggregate_query_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_aggregate_query_stats_pager(transport_name: str = "grpc"): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + next_page_token="abc", + ), + service.AggregateQueryStatsResponse( + query_stats=[], + next_page_token="def", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + ], + next_page_token="ghi", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.aggregate_query_stats(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service.QueryStatsInfo) for i in results) + + +def test_aggregate_query_stats_pages(transport_name: str = "grpc"): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + next_page_token="abc", + ), + service.AggregateQueryStatsResponse( + query_stats=[], + next_page_token="def", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + ], + next_page_token="ghi", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + ), + RuntimeError, + ) + pages = list(client.aggregate_query_stats(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_aggregate_query_stats_async_pager(): + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + next_page_token="abc", + ), + service.AggregateQueryStatsResponse( + query_stats=[], + next_page_token="def", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + ], + next_page_token="ghi", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + ), + RuntimeError, + ) + async_pager = await client.aggregate_query_stats( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, service.QueryStatsInfo) for i in responses) + + +@pytest.mark.asyncio +async def test_aggregate_query_stats_async_pages(): + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + next_page_token="abc", + ), + service.AggregateQueryStatsResponse( + query_stats=[], + next_page_token="def", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + ], + next_page_token="ghi", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.aggregate_query_stats(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + @pytest.mark.parametrize( "request_type", [ @@ -3727,22 +4191,148 @@ def test_query_database_resource_groups_rest_pager(transport: str = "rest"): return_val.status_code = 200 req.side_effect = return_values - sample_request = {} + sample_request = {} + + pager = client.query_database_resource_groups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service.DatabaseResourceGroup) for i in results) + + pages = list( + client.query_database_resource_groups(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_aggregate_issue_stats_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.aggregate_issue_stats + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.aggregate_issue_stats] = ( + mock_rpc + ) + + request = {} + client.aggregate_issue_stats(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.aggregate_issue_stats(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_aggregate_issue_stats_rest_required_fields( + request_type=service.AggregateIssueStatsRequest, +): + transport_class = transports.DatabaseCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregate_issue_stats._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregate_issue_stats._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.AggregateIssueStatsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.AggregateIssueStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.aggregate_issue_stats(request) - pager = client.query_database_resource_groups(request=sample_request) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, service.DatabaseResourceGroup) for i in results) - pages = list( - client.query_database_resource_groups(request=sample_request).pages - ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_aggregate_issue_stats_rest_unset_required_fields(): + transport = transports.DatabaseCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.aggregate_issue_stats._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) -def test_aggregate_issue_stats_rest_use_cached_wrapped_rpc(): +def test_aggregate_query_stats_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3757,7 +4347,7 @@ def test_aggregate_issue_stats_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.aggregate_issue_stats + client._transport.aggregate_query_stats in client._transport._wrapped_methods ) @@ -3766,25 +4356,25 @@ def test_aggregate_issue_stats_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.aggregate_issue_stats] = ( + client._transport._wrapped_methods[client._transport.aggregate_query_stats] = ( mock_rpc ) request = {} - client.aggregate_issue_stats(request) + client.aggregate_query_stats(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.aggregate_issue_stats(request) + client.aggregate_query_stats(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_aggregate_issue_stats_rest_required_fields( - request_type=service.AggregateIssueStatsRequest, +def test_aggregate_query_stats_rest_required_fields( + request_type=service.AggregateQueryStatsRequest, ): transport_class = transports.DatabaseCenterRestTransport @@ -3800,7 +4390,7 @@ def test_aggregate_issue_stats_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).aggregate_issue_stats._get_unset_required_fields(jsonified_request) + ).aggregate_query_stats._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -3809,7 +4399,7 @@ def test_aggregate_issue_stats_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).aggregate_issue_stats._get_unset_required_fields(jsonified_request) + ).aggregate_query_stats._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3823,7 +4413,7 @@ def test_aggregate_issue_stats_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.AggregateIssueStatsResponse() + return_value = service.AggregateQueryStatsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -3845,29 +4435,92 @@ def test_aggregate_issue_stats_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.AggregateIssueStatsResponse.pb(return_value) + return_value = service.AggregateQueryStatsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.aggregate_issue_stats(request) + response = client.aggregate_query_stats(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_aggregate_issue_stats_rest_unset_required_fields(): +def test_aggregate_query_stats_rest_unset_required_fields(): transport = transports.DatabaseCenterRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.aggregate_issue_stats._get_unset_required_fields({}) + unset_fields = transport.aggregate_query_stats._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("parent",))) +def test_aggregate_query_stats_rest_pager(transport: str = "rest"): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + next_page_token="abc", + ), + service.AggregateQueryStatsResponse( + query_stats=[], + next_page_token="def", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + ], + next_page_token="ghi", + ), + service.AggregateQueryStatsResponse( + query_stats=[ + service.QueryStatsInfo(), + service.QueryStatsInfo(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.AggregateQueryStatsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1"} + + pager = client.aggregate_query_stats(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service.QueryStatsInfo) for i in results) + + pages = list(client.aggregate_query_stats(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + def test_query_issues_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4298,6 +4951,29 @@ def test_aggregate_issue_stats_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_aggregate_query_stats_empty_call_grpc(): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + call.return_value = service.AggregateQueryStatsResponse() + client.aggregate_query_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AggregateQueryStatsRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_query_issues_empty_call_grpc(): @@ -4452,6 +5128,36 @@ async def test_aggregate_issue_stats_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_aggregate_query_stats_empty_call_grpc_asyncio(): + client = DatabaseCenterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.AggregateQueryStatsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.aggregate_query_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AggregateQueryStatsRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -5033,6 +5739,144 @@ def test_aggregate_issue_stats_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_aggregate_query_stats_rest_bad_request( + request_type=service.AggregateQueryStatsRequest, +): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.aggregate_query_stats(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.AggregateQueryStatsRequest, + dict, + ], +) +def test_aggregate_query_stats_rest_call_success(request_type): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.AggregateQueryStatsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.AggregateQueryStatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.aggregate_query_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AggregateQueryStatsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_aggregate_query_stats_rest_interceptors(null_interceptor): + transport = transports.DatabaseCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DatabaseCenterRestInterceptor(), + ) + client = DatabaseCenterClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DatabaseCenterRestInterceptor, "post_aggregate_query_stats" + ) as post, + mock.patch.object( + transports.DatabaseCenterRestInterceptor, + "post_aggregate_query_stats_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DatabaseCenterRestInterceptor, "pre_aggregate_query_stats" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.AggregateQueryStatsRequest.pb( + service.AggregateQueryStatsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.AggregateQueryStatsResponse.to_json( + service.AggregateQueryStatsResponse() + ) + req.return_value.content = return_value + + request = service.AggregateQueryStatsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.AggregateQueryStatsResponse() + post_with_metadata.return_value = ( + service.AggregateQueryStatsResponse(), + metadata, + ) + + client.aggregate_query_stats( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_query_issues_rest_bad_request(request_type=service.QueryIssuesRequest): client = DatabaseCenterClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -5254,6 +6098,28 @@ def test_aggregate_issue_stats_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_aggregate_query_stats_empty_call_rest(): + client = DatabaseCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.aggregate_query_stats), "__call__" + ) as call: + client.aggregate_query_stats(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AggregateQueryStatsRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_query_issues_empty_call_rest(): @@ -5311,6 +6177,7 @@ def test_database_center_base_transport(): "aggregate_fleet", "query_database_resource_groups", "aggregate_issue_stats", + "aggregate_query_stats", "query_issues", ) for method in methods: @@ -5589,6 +6456,9 @@ def test_database_center_client_transport_session_collision(transport_name): session1 = client1.transport.aggregate_issue_stats._session session2 = client2.transport.aggregate_issue_stats._session assert session1 != session2 + session1 = client1.transport.aggregate_query_stats._session + session2 = client2.transport.aggregate_query_stats._session + assert session1 != session2 session1 = client1.transport.query_issues._session session2 = client2.transport.query_issues._session assert session1 != session2 diff --git a/packages/google-cloud-storage/google/cloud/storage/bucket.py b/packages/google-cloud-storage/google/cloud/storage/bucket.py index ba5b59c8cb26..e39d430ac958 100644 --- a/packages/google-cloud-storage/google/cloud/storage/bucket.py +++ b/packages/google-cloud-storage/google/cloud/storage/bucket.py @@ -41,8 +41,7 @@ from google.cloud.storage._opentelemetry_tracing import create_trace_span from google.cloud.storage._signing import generate_signed_url_v2, generate_signed_url_v4 from google.cloud.storage.acl import BucketACL, DefaultObjectACL -from google.cloud.storage.blob import Blob, _quote -from google.cloud.storage.blob import ObjectContexts +from google.cloud.storage.blob import Blob, ObjectContexts, _quote from google.cloud.storage.constants import ( _DEFAULT_TIMEOUT, ARCHIVE_STORAGE_CLASS, diff --git a/packages/google-cloud-storage/tests/system/test_zonal.py b/packages/google-cloud-storage/tests/system/test_zonal.py index 4c3d606abd23..20e172a1adee 100644 --- a/packages/google-cloud-storage/tests/system/test_zonal.py +++ b/packages/google-cloud-storage/tests/system/test_zonal.py @@ -18,14 +18,14 @@ _DEFAULT_FLUSH_INTERVAL_BYTES, AsyncAppendableObjectWriter, ) -from google.cloud.storage.blob import ( - ObjectContexts, - ObjectCustomContextPayload, -) from google.cloud.storage.asyncio.async_grpc_client import AsyncGrpcClient from google.cloud.storage.asyncio.async_multi_range_downloader import ( AsyncMultiRangeDownloader, ) +from google.cloud.storage.blob import ( + ObjectContexts, + ObjectCustomContextPayload, +) pytestmark = pytest.mark.skipif( os.getenv("RUN_ZONAL_SYSTEM_TESTS") != "True", diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_write_object_stream.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_write_object_stream.py index a73828345aa7..2fcca43b0882 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_write_object_stream.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_write_object_stream.py @@ -21,10 +21,10 @@ from google.cloud import _storage_v2 from google.cloud.storage import Blob, Bucket -from google.cloud.storage.blob import ObjectContexts, ObjectCustomContextPayload from google.cloud.storage.asyncio.async_write_object_stream import ( _AsyncWriteObjectStream, ) +from google.cloud.storage.blob import ObjectContexts, ObjectCustomContextPayload BUCKET = "my-bucket" OBJECT = "my-object"