diff --git a/.librarian/state.yaml b/.librarian/state.yaml index 205f9b20f6c4..4e385e101fb3 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -2,7 +2,7 @@ image: us-central1-docker.pkg.dev/cloud-sdk-librarian-prod/images-prod/python-li libraries: - id: google-ads-admanager version: 0.4.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/ads/admanager/v1 service_config: admanager_v1.yaml @@ -21,7 +21,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-ads-marketingplatform-admin version: 0.1.6 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/marketingplatform/admin/v1alpha service_config: marketingplatformadmin_v1alpha.yaml @@ -40,7 +40,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-ai-generativelanguage version: 0.7.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/ai/generativelanguage/v1 service_config: generativelanguage_v1.yaml @@ -67,7 +67,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-analytics-admin version: 0.25.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/analytics/admin/v1beta service_config: analyticsadmin_v1beta.yaml @@ -88,7 +88,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-analytics-data version: 0.18.19 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/analytics/data/v1alpha service_config: analyticsdata_v1alpha.yaml @@ -109,7 +109,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-apps-card version: 0.1.8 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/apps/card/v1 service_config: "" @@ -129,7 +129,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-apps-chat version: 0.2.9 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/chat/v1 service_config: chat_v1.yaml @@ -148,7 +148,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-apps-events-subscriptions version: 0.2.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/apps/events/subscriptions/v1 service_config: workspaceevents_v1.yaml @@ -169,7 +169,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-apps-meet version: 0.1.16 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/apps/meet/v2beta service_config: meet_v2beta.yaml @@ -190,7 +190,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-area120-tables version: 0.11.17 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/area120/tables/v1alpha1 service_config: area120tables_v1alpha1.yaml @@ -209,7 +209,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-access-approval version: 1.16.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/accessapproval/v1 service_config: accessapproval_v1.yaml @@ -228,7 +228,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-access-context-manager version: 0.2.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/identity/accesscontextmanager/v1 service_config: accesscontextmanager_v1.yaml @@ -242,7 +242,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-advisorynotifications version: 0.3.16 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/advisorynotifications/v1 service_config: advisorynotifications_v1.yaml @@ -261,7 +261,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-alloydb version: 0.5.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/alloydb/v1beta service_config: alloydb_v1beta.yaml @@ -284,7 +284,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-alloydb-connectors version: 0.1.11 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/alloydb/connectors/v1 service_config: connectors_v1.yaml @@ -308,7 +308,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-api-gateway version: 1.12.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/apigateway/v1 service_config: apigateway_v1.yaml @@ -327,7 +327,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-api-keys version: 0.5.17 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/api/apikeys/v2 service_config: apikeys_v2.yaml @@ -346,7 +346,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-apigee-connect version: 1.12.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/apigeeconnect/v1 service_config: apigeeconnect_v1.yaml @@ -365,7 +365,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-apigee-registry version: 0.6.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/apigeeregistry/v1 service_config: apigeeregistry_v1.yaml @@ -384,7 +384,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-apihub version: 0.3.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/apihub/v1 service_config: apihub_v1.yaml @@ -403,7 +403,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-appengine-admin version: 1.14.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/appengine/v1 service_config: appengine_v1.yaml @@ -422,7 +422,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-appengine-logging version: 1.6.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/appengine/logging/v1 service_config: "" @@ -442,7 +442,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-apphub version: 0.1.10 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/apphub/v1 service_config: apphub_v1.yaml @@ -461,7 +461,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-artifact-registry version: 1.16.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/devtools/artifactregistry/v1 service_config: artifactregistry_v1.yaml @@ -482,7 +482,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-asset version: 4.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/asset/v1p5beta1 service_config: cloudasset_v1p5beta1.yaml @@ -507,7 +507,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-assured-workloads version: 2.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/assuredworkloads/v1 service_config: assuredworkloads_v1.yaml @@ -528,7 +528,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-audit-log version: 0.3.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/audit service_config: cloudaudit.yaml @@ -540,7 +540,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-automl version: 2.16.4 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/automl/v1beta1 service_config: automl_v1beta1.yaml @@ -566,7 +566,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-backupdr version: 0.2.5 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/backupdr/v1 service_config: backupdr_v1.yaml @@ -585,7 +585,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bare-metal-solution version: 1.10.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/baremetalsolution/v2 service_config: baremetalsolution_v2.yaml @@ -604,7 +604,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-batch version: 0.17.37 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/batch/v1alpha service_config: batch_v1alpha.yaml @@ -625,7 +625,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-beyondcorp-appconnections version: 0.4.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/beyondcorp/appconnections/v1 service_config: beyondcorp_v1.yaml @@ -644,7 +644,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-beyondcorp-appconnectors version: 0.4.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/beyondcorp/appconnectors/v1 service_config: beyondcorp_v1.yaml @@ -663,7 +663,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-beyondcorp-appgateways version: 0.4.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/beyondcorp/appgateways/v1 service_config: beyondcorp_v1.yaml @@ -682,7 +682,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-beyondcorp-clientconnectorservices version: 0.4.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/beyondcorp/clientconnectorservices/v1 service_config: beyondcorp_v1.yaml @@ -701,7 +701,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-beyondcorp-clientgateways version: 0.4.17 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/beyondcorp/clientgateways/v1 service_config: beyondcorp_v1.yaml @@ -720,7 +720,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-analyticshub version: 0.4.20 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/analyticshub/v1 service_config: analyticshub_v1.yaml @@ -739,7 +739,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-biglake version: 0.4.15 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/biglake/v1alpha1 service_config: biglake_v1alpha1.yaml @@ -760,7 +760,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-connection version: 1.18.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/connection/v1 service_config: bigqueryconnection_v1.yaml @@ -779,7 +779,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-data-exchange version: 0.5.20 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/dataexchange/v1beta1 service_config: analyticshub_v1beta1.yaml @@ -798,7 +798,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-datapolicies version: 0.6.16 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/datapolicies/v2beta1 service_config: bigquerydatapolicy_v2beta1.yaml @@ -823,7 +823,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-datatransfer version: 3.19.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/datatransfer/v1 service_config: bigquerydatatransfer_v1.yaml @@ -842,7 +842,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-logging version: 1.6.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/logging/v1 service_config: "" @@ -862,7 +862,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-migration version: 0.11.15 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/migration/v2alpha service_config: bigquerymigration_v2alpha.yaml @@ -883,7 +883,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-bigquery-reservation version: 1.20.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/bigquery/reservation/v1 service_config: bigqueryreservation_v1.yaml @@ -902,7 +902,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-billing version: 1.16.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/billing/v1 service_config: cloudbilling_v1.yaml @@ -921,7 +921,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-billing-budgets version: 1.17.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/billing/budgets/v1 service_config: billingbudgets.yaml @@ -942,7 +942,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-binary-authorization version: 1.13.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/binaryauthorization/v1 service_config: binaryauthorization_v1.yaml @@ -963,7 +963,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-build version: 3.32.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/devtools/cloudbuild/v1 service_config: cloudbuild_v1.yaml @@ -984,7 +984,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-capacityplanner version: 0.1.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/capacityplanner/v1beta service_config: capacityplanner_v1beta.yaml @@ -1003,7 +1003,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-certificate-manager version: 1.10.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/certificatemanager/v1 service_config: certificatemanager_v1.yaml @@ -1022,7 +1022,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-channel version: 1.23.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/channel/v1 service_config: cloudchannel_v1.yaml @@ -1041,7 +1041,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-chronicle version: 0.1.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/chronicle/v1 service_config: chronicle_v1.yaml @@ -1060,7 +1060,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-cloudcontrolspartner version: 0.2.7 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/cloudcontrolspartner/v1beta service_config: cloudcontrolspartner_v1beta.yaml @@ -1081,7 +1081,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-cloudsecuritycompliance version: 0.2.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/cloudsecuritycompliance/v1 service_config: cloudsecuritycompliance_v1.yaml @@ -1100,7 +1100,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-commerce-consumer-procurement version: 0.2.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/commerce/consumer/procurement/v1 service_config: cloudcommerceconsumerprocurement_v1.yaml @@ -1121,7 +1121,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-common version: 1.5.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/common service_config: common.yaml @@ -1141,7 +1141,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-compute version: 1.39.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/compute/v1 service_config: compute_v1.yaml @@ -1160,7 +1160,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-compute-v1beta version: 0.2.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/compute/v1beta service_config: compute_v1beta.yaml @@ -1179,7 +1179,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-confidentialcomputing version: 0.5.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/confidentialcomputing/v1 service_config: confidentialcomputing_v1.yaml @@ -1198,7 +1198,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-config version: 0.1.21 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/config/v1 service_config: config_v1.yaml @@ -1217,7 +1217,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-configdelivery version: 0.1.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/configdelivery/v1beta service_config: configdelivery_v1beta.yaml @@ -1240,7 +1240,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-contact-center-insights version: 1.23.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/contactcenterinsights/v1 service_config: contactcenterinsights_v1.yaml @@ -1259,7 +1259,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-container version: 2.59.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/container/v1 service_config: container_v1.yaml @@ -1280,7 +1280,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-containeranalysis version: 2.18.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/devtools/containeranalysis/v1 service_config: containeranalysis_v1.yaml @@ -1300,7 +1300,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-contentwarehouse version: 0.7.16 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/contentwarehouse/v1 service_config: contentwarehouse_v1.yaml @@ -1319,7 +1319,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-data-fusion version: 1.13.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/datafusion/v1 service_config: datafusion_v1.yaml @@ -1338,7 +1338,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-data-qna version: 0.10.17 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/dataqna/v1alpha service_config: dataqna_v1alpha.yaml @@ -1357,7 +1357,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-datacatalog version: 3.27.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/datacatalog/v1 service_config: datacatalog_v1.yaml @@ -1378,7 +1378,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-datacatalog-lineage version: 0.3.14 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/datacatalog/lineage/v1 service_config: datalineage_v1.yaml @@ -1397,7 +1397,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dataflow-client version: 0.9.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/dataflow/v1beta3 service_config: dataflow_v1beta3.yaml @@ -1416,7 +1416,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dataform version: 0.6.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/dataform/v1beta1 service_config: dataform_v1beta1.yaml @@ -1437,7 +1437,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-datalabeling version: 1.13.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/datalabeling/v1beta1 service_config: datalabeling_v1beta1.yaml @@ -1456,7 +1456,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dataplex version: 2.12.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/dataplex/v1 service_config: dataplex_v1.yaml @@ -1475,7 +1475,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dataproc version: 5.22.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/dataproc/v1 service_config: dataproc_v1.yaml @@ -1494,7 +1494,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dataproc-metastore version: 1.19.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/metastore/v1alpha service_config: metastore_v1alpha.yaml @@ -1517,7 +1517,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-datastream version: 1.15.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/datastream/v1 service_config: datastream_v1.yaml @@ -1538,7 +1538,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-deploy version: 2.7.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/deploy/v1 service_config: clouddeploy_v1.yaml @@ -1557,7 +1557,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-developerconnect version: 0.1.10 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/developerconnect/v1 service_config: developerconnect_v1.yaml @@ -1576,7 +1576,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-devicestreaming version: 0.1.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/devicestreaming/v1 service_config: devicestreaming_v1.yaml @@ -1595,7 +1595,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dialogflow version: 2.41.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/dialogflow/v2beta1 service_config: dialogflow_v2beta1.yaml @@ -1616,7 +1616,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-discoveryengine version: 0.13.12 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/discoveryengine/v1 service_config: discoveryengine_v1.yaml @@ -1639,7 +1639,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dlp version: 3.32.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/privacy/dlp/v2 service_config: dlp_v2.yaml @@ -1658,7 +1658,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dms version: 1.12.4 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/clouddms/v1 service_config: datamigration_v1.yaml @@ -1677,7 +1677,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-documentai version: 3.6.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/documentai/v1beta3 service_config: documentai_v1beta3.yaml @@ -1698,7 +1698,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-domains version: 1.10.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/domains/v1beta1 service_config: domains_v1beta1.yaml @@ -1719,7 +1719,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-edgecontainer version: 0.5.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/edgecontainer/v1 service_config: edgecontainer_v1.yaml @@ -1738,7 +1738,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-edgenetwork version: 0.1.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/edgenetwork/v1 service_config: edgenetwork_v1.yaml @@ -1757,7 +1757,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-enterpriseknowledgegraph version: 0.3.17 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/enterpriseknowledgegraph/v1 service_config: enterpriseknowledgegraph_v1.yaml @@ -1776,7 +1776,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-essential-contacts version: 1.10.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/essentialcontacts/v1 service_config: essentialcontacts_v1.yaml @@ -1795,7 +1795,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-eventarc version: 1.16.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/eventarc/v1 service_config: eventarc_v1.yaml @@ -1814,7 +1814,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-eventarc-publishing version: 0.7.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/eventarc/publishing/v1 service_config: eventarcpublishing_v1.yaml @@ -1833,7 +1833,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-filestore version: 1.13.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/filestore/v1 service_config: file_v1.yaml @@ -1852,7 +1852,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-financialservices version: 0.1.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/financialservices/v1 service_config: financialservices_v1.yaml @@ -1871,7 +1871,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-functions version: 1.20.4 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/functions/v2 service_config: cloudfunctions_v2.yaml @@ -1892,7 +1892,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-gdchardwaremanagement version: 0.1.13 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/gdchardwaremanagement/v1alpha service_config: gdchardwaremanagement_v1alpha.yaml @@ -1911,7 +1911,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-geminidataanalytics version: 0.4.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/geminidataanalytics/v1beta service_config: geminidataanalytics_v1beta.yaml @@ -1932,7 +1932,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-gke-backup version: 0.5.19 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/gkebackup/v1 service_config: gkebackup_v1.yaml @@ -1951,7 +1951,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-gke-connect-gateway version: 0.10.4 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/gkeconnect/gateway/v1beta1 service_config: connectgateway_v1beta1.yaml @@ -1972,7 +1972,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-iam-logging version: 1.4.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/iam/v1/logging service_config: "" @@ -1992,7 +1992,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-iap version: 1.17.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/iap/v1 service_config: iap_v1.yaml @@ -2011,7 +2011,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-ids version: 1.10.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/ids/v1 service_config: ids_v1.yaml @@ -2030,7 +2030,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-kms version: 3.6.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/kms/v1 service_config: cloudkms_v1.yaml @@ -2049,7 +2049,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-kms-inventory version: 0.2.15 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/kms/inventory/v1 service_config: kmsinventory_v1.yaml @@ -2068,7 +2068,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-language version: 2.17.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/language/v1 service_config: language_v1.yaml @@ -2091,7 +2091,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-licensemanager version: 0.1.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/licensemanager/v1 service_config: licensemanager_v1.yaml @@ -2110,7 +2110,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-life-sciences version: 0.9.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/lifesciences/v2beta service_config: lifesciences_v2beta.yaml @@ -2129,7 +2129,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-locationfinder version: 0.1.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/locationfinder/v1 service_config: cloudlocationfinder_v1.yaml @@ -2148,7 +2148,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-lustre version: 0.1.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/lustre/v1 service_config: lustre_v1.yaml @@ -2167,7 +2167,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-maintenance-api version: 0.1.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/maintenance/api/v1beta service_config: maintenance_v1beta.yaml @@ -2186,7 +2186,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-managed-identities version: 1.12.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/managedidentities/v1 service_config: managedidentities_v1.yaml @@ -2205,7 +2205,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-managedkafka version: 0.1.12 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/managedkafka/v1 service_config: managedkafka_v1.yaml @@ -2224,7 +2224,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-managedkafka-schemaregistry version: 0.1.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/managedkafka/schemaregistry/v1 service_config: managedkafka_v1.yaml @@ -2243,7 +2243,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-media-translation version: 0.11.17 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/mediatranslation/v1beta1 service_config: mediatranslation_v1beta1.yaml @@ -2262,7 +2262,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-memcache version: 1.12.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/memcache/v1 service_config: memcache_v1.yaml @@ -2283,7 +2283,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-memorystore version: 0.1.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/memorystore/v1beta service_config: memorystore_v1beta.yaml @@ -2304,7 +2304,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-migrationcenter version: 0.1.15 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/migrationcenter/v1 service_config: migrationcenter_v1.yaml @@ -2323,7 +2323,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-modelarmor version: 0.2.8 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/modelarmor/v1beta service_config: modelarmor_v1beta.yaml @@ -2344,7 +2344,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-monitoring-metrics-scopes version: 1.9.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/monitoring/metricsscope/v1 service_config: monitoring.yaml @@ -2363,7 +2363,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-netapp version: 0.3.24 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/netapp/v1 service_config: netapp_v1.yaml @@ -2382,7 +2382,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-network-connectivity version: 2.10.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/networkconnectivity/v1 service_config: networkconnectivity_v1.yaml @@ -2403,7 +2403,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-network-management version: 1.28.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/networkmanagement/v1 service_config: networkmanagement_v1.yaml @@ -2422,7 +2422,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-network-services version: 0.5.24 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/networkservices/v1 service_config: networkservices_v1.yaml @@ -2441,7 +2441,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-notebooks version: 1.13.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/notebooks/v1beta1 service_config: notebooks_v1beta1.yaml @@ -2464,7 +2464,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-optimization version: 1.11.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/optimization/v1 service_config: cloudoptimization_v1.yaml @@ -2483,7 +2483,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-oracledatabase version: 0.1.10 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/oracledatabase/v1 service_config: oracledatabase_v1.yaml @@ -2502,7 +2502,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-orchestration-airflow version: 1.17.5 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/orchestration/airflow/service/v1 service_config: composer_v1.yaml @@ -2523,7 +2523,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-os-config version: 1.21.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/osconfig/v1alpha service_config: osconfig_v1alpha.yaml @@ -2544,7 +2544,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-parallelstore version: 0.2.15 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/parallelstore/v1 service_config: parallelstore_v1.yaml @@ -2565,7 +2565,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-parametermanager version: 0.1.5 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/parametermanager/v1 service_config: parametermanager_v1.yaml @@ -2584,7 +2584,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-phishing-protection version: 1.14.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/phishingprotection/v1beta1 service_config: phishingprotection_v1beta1.yaml @@ -2603,7 +2603,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-policy-troubleshooter version: 1.13.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/policytroubleshooter/v1 service_config: policytroubleshooter_v1.yaml @@ -2622,7 +2622,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-policysimulator version: 0.1.15 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/policysimulator/v1 service_config: policysimulator_v1.yaml @@ -2641,7 +2641,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-policytroubleshooter-iam version: 0.1.13 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/policytroubleshooter/iam/v3 service_config: policytroubleshooter_v3.yaml @@ -2660,7 +2660,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-private-ca version: 1.15.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/security/privateca/v1 service_config: privateca_v1.yaml @@ -2681,7 +2681,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-private-catalog version: 0.9.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/privatecatalog/v1beta1 service_config: cloudprivatecatalog_v1beta1.yaml @@ -2700,7 +2700,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-privilegedaccessmanager version: 0.1.9 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/privilegedaccessmanager/v1 service_config: privilegedaccessmanager_v1.yaml @@ -2719,7 +2719,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-quotas version: 0.1.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/api/cloudquotas/v1 service_config: cloudquotas_v1.yaml @@ -2740,7 +2740,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-rapidmigrationassessment version: 0.1.16 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/rapidmigrationassessment/v1 service_config: rapidmigrationassessment_v1.yaml @@ -2759,7 +2759,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-recaptcha-enterprise version: 1.28.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/recaptchaenterprise/v1 service_config: recaptchaenterprise_v1.yaml @@ -2778,7 +2778,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-recommendations-ai version: 0.10.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/recommendationengine/v1beta1 service_config: recommendationengine_v1beta1.yaml @@ -2797,7 +2797,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-recommender version: 2.18.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/recommender/v1beta1 service_config: recommender_v1beta1.yaml @@ -2818,7 +2818,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-redis version: 2.18.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/redis/v1 service_config: redis_v1.yaml @@ -2839,7 +2839,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-redis-cluster version: 0.1.15 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/redis/cluster/v1 service_config: redis_v1.yaml @@ -2860,7 +2860,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-resource-manager version: 1.14.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/resourcemanager/v3 service_config: cloudresourcemanager_v3.yaml @@ -2879,7 +2879,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-retail version: 2.6.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/retail/v2 service_config: retail_v2.yaml @@ -2902,7 +2902,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-run version: 0.11.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/run/v2 service_config: run_v2.yaml @@ -2921,7 +2921,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-saasplatform-saasservicemgmt version: 0.1.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/saasplatform/saasservicemgmt/v1beta1 service_config: saasservicemgmt_v1beta1.yaml @@ -2940,7 +2940,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-scheduler version: 2.16.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/scheduler/v1 service_config: cloudscheduler_v1.yaml @@ -2961,7 +2961,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-securesourcemanager version: 0.1.17 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/securesourcemanager/v1 service_config: securesourcemanager_v1.yaml @@ -2980,7 +2980,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-security-publicca version: 0.3.18 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/security/publicca/v1 service_config: publicca_v1.yaml @@ -3001,7 +3001,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-securitycenter version: 1.40.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/securitycenter/v2 service_config: securitycenter_v2.yaml @@ -3026,7 +3026,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-securitycentermanagement version: 0.1.22 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/securitycentermanagement/v1 service_config: securitycentermanagement_v1.yaml @@ -3045,7 +3045,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-service-control version: 1.16.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/api/servicecontrol/v2 service_config: servicecontrol.yaml @@ -3066,7 +3066,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-service-directory version: 1.14.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/servicedirectory/v1 service_config: servicedirectory_v1.yaml @@ -3087,7 +3087,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-service-management version: 1.13.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/api/servicemanagement/v1 service_config: servicemanagement_v1.yaml @@ -3106,7 +3106,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-service-usage version: 1.13.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/api/serviceusage/v1 service_config: serviceusage_v1.yaml @@ -3125,7 +3125,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-servicehealth version: 0.1.12 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/servicehealth/v1 service_config: servicehealth_v1.yaml @@ -3144,7 +3144,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-shell version: 1.12.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/shell/v1 service_config: cloudshell_v1.yaml @@ -3163,7 +3163,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-source-context version: 1.7.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/devtools/source/v1 service_config: "" @@ -3183,7 +3183,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-speech version: 2.33.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/speech/v1 service_config: speech_v1.yaml @@ -3208,7 +3208,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-storage-control version: 1.7.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/storage/control/v2 service_config: storage_v2.yaml @@ -3227,7 +3227,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-storage-transfer version: 1.17.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/storagetransfer/v1 service_config: storagetransfer_v1.yaml @@ -3246,7 +3246,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-storagebatchoperations version: 0.1.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/storagebatchoperations/v1 service_config: storagebatchoperations_v1.yaml @@ -3265,7 +3265,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-storageinsights version: 0.1.16 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/storageinsights/v1 service_config: storageinsights_v1.yaml @@ -3284,7 +3284,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-support version: 0.1.19 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/support/v2beta service_config: cloudsupport_v2beta.yaml @@ -3305,7 +3305,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-talent version: 2.17.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/talent/v4beta1 service_config: jobs_v4beta1.yaml @@ -3326,7 +3326,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-tasks version: 2.19.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/tasks/v2beta2 service_config: cloudtasks_v2beta2.yaml @@ -3350,7 +3350,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-telcoautomation version: 0.2.11 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/telcoautomation/v1 service_config: telcoautomation_v1.yaml @@ -3372,7 +3372,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-texttospeech version: 2.31.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/texttospeech/v1 service_config: texttospeech_v1.yaml @@ -3393,7 +3393,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-tpu version: 1.23.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/tpu/v2alpha1 service_config: tpu_v2alpha1.yaml @@ -3416,7 +3416,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-trace version: 1.16.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/devtools/cloudtrace/v2 service_config: cloudtrace_v2.yaml @@ -3437,7 +3437,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-translate version: 3.21.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/translate/v3beta1 service_config: translate_v3beta1.yaml @@ -3462,7 +3462,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-video-live-stream version: 1.13.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/video/livestream/v1 service_config: livestream_v1.yaml @@ -3481,7 +3481,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-video-stitcher version: 0.8.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/video/stitcher/v1 service_config: videostitcher_v1.yaml @@ -3500,7 +3500,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-video-transcoder version: 1.17.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/video/transcoder/v1 service_config: transcoder_v1.yaml @@ -3519,7 +3519,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-videointelligence version: 2.16.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/videointelligence/v1p3beta1 service_config: videointelligence_v1p3beta1.yaml @@ -3546,7 +3546,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-vision version: 3.10.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/vision/v1p3beta1 service_config: vision_v1p3beta1.yaml @@ -3576,7 +3576,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-visionai version: 0.1.10 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/visionai/v1alpha1 service_config: visionai_v1alpha1.yaml @@ -3597,7 +3597,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-vm-migration version: 1.12.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/vmmigration/v1 service_config: vmmigration_v1.yaml @@ -3616,7 +3616,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-vmwareengine version: 1.8.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/vmwareengine/v1 service_config: vmwareengine_v1.yaml @@ -3635,7 +3635,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-vpc-access version: 1.13.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/vpcaccess/v1 service_config: vpcaccess_v1.yaml @@ -3654,7 +3654,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-webrisk version: 1.18.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/webrisk/v1beta1 service_config: webrisk_v1beta1.yaml @@ -3675,7 +3675,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-websecurityscanner version: 1.17.3 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/websecurityscanner/v1alpha service_config: websecurityscanner_v1alpha.yaml @@ -3698,7 +3698,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-workflows version: 1.18.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/workflows/executions/v1 service_config: workflowexecutions_v1.yaml @@ -3723,7 +3723,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-workstations version: 0.5.15 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/cloud/workstations/v1beta service_config: workstations_v1beta.yaml @@ -3744,7 +3744,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-geo-type version: 0.3.13 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/geo/type service_config: type_geo.yaml @@ -3764,7 +3764,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-addressvalidation version: 0.3.20 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/addressvalidation/v1 service_config: addressvalidation_v1.yaml @@ -3783,7 +3783,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-areainsights version: 0.1.8 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/areainsights/v1 service_config: areainsights_v1.yaml @@ -3802,7 +3802,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-fleetengine version: 0.2.11 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/fleetengine/v1 service_config: fleetengine_v1.yaml @@ -3821,7 +3821,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-fleetengine-delivery version: 0.2.13 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/fleetengine/delivery/v1 service_config: fleetengine_v1.yaml @@ -3840,7 +3840,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-mapsplatformdatasets version: 0.4.8 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/mapsplatformdatasets/v1 service_config: mapsplatformdatasets_v1.yaml @@ -3859,7 +3859,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-places version: 0.2.2 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/places/v1 service_config: places_v1.yaml @@ -3878,7 +3878,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-routeoptimization version: 0.1.11 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/routeoptimization/v1 service_config: routeoptimization_v1.yaml @@ -3898,7 +3898,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-routing version: 0.6.16 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/routing/v2 service_config: routes_v2.yaml @@ -3917,7 +3917,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-maps-solar version: 0.1.9 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/maps/solar/v1 service_config: solar_v1.yaml @@ -3936,7 +3936,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-css version: 0.1.17 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/css/v1 service_config: css_v1.yaml @@ -3955,7 +3955,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-accounts version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/accounts/v1 service_config: merchantapi_v1.yaml @@ -3976,7 +3976,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-conversions version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/conversions/v1 service_config: merchantapi_v1.yaml @@ -3997,7 +3997,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-datasources version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/datasources/v1 service_config: merchantapi_v1.yaml @@ -4018,7 +4018,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-inventories version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/inventories/v1beta service_config: merchantapi_v1beta.yaml @@ -4039,7 +4039,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-issueresolution version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/issueresolution/v1 service_config: merchantapi_v1.yaml @@ -4060,7 +4060,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-lfp version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/lfp/v1beta service_config: merchantapi_v1beta.yaml @@ -4081,7 +4081,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-notifications version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/notifications/v1 service_config: merchantapi_v1.yaml @@ -4102,7 +4102,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-ordertracking version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/ordertracking/v1 service_config: merchantapi_v1.yaml @@ -4123,7 +4123,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-products version: 1.1.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/products/v1 service_config: merchantapi_v1.yaml @@ -4144,7 +4144,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-productstudio version: 0.1.1 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/productstudio/v1alpha service_config: merchantapi_v1alpha.yaml @@ -4163,7 +4163,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-promotions version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/promotions/v1 service_config: merchantapi_v1.yaml @@ -4184,7 +4184,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-quota version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/quota/v1beta service_config: merchantapi_v1beta.yaml @@ -4205,7 +4205,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-reports version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/reports/v1beta service_config: merchantapi_v1beta.yaml @@ -4228,7 +4228,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-merchant-reviews version: 0.2.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/merchant/reviews/v1beta service_config: merchantapi_v1beta.yaml @@ -4247,7 +4247,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-shopping-type version: 1.0.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/shopping/type service_config: "" @@ -4267,7 +4267,7 @@ libraries: tag_format: '{id}-v{version}' - id: googleapis-common-protos version: 1.70.0 - last_generated_commit: 50a2632056a4678661e5ee309ceb83d00f5ddbf5 + last_generated_commit: 102d9f92ac6ed649a61efd9b208e4d1de278e9bb apis: - path: google/api service_config: serviceconfig.yaml diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_health_sources.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_health_sources.rst new file mode 100644 index 000000000000..ab7cea32470b --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_health_sources.rst @@ -0,0 +1,10 @@ +RegionHealthSources +------------------------------------- + +.. automodule:: google.cloud.compute_v1beta.services.region_health_sources + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.region_health_sources.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_network_policies.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_network_policies.rst new file mode 100644 index 000000000000..8817bb92b79d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_network_policies.rst @@ -0,0 +1,10 @@ +RegionNetworkPolicies +--------------------------------------- + +.. automodule:: google.cloud.compute_v1beta.services.region_network_policies + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.region_network_policies.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst index 205fd51fc6c6..f0a2044680b5 100644 --- a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst @@ -67,6 +67,7 @@ Services for Google Cloud Compute v1beta API region_disk_types region_health_checks region_health_check_services + region_health_sources region_instance_group_manager_resize_requests region_instance_group_managers region_instance_groups @@ -76,6 +77,7 @@ Services for Google Cloud Compute v1beta API region_multi_migs region_network_endpoint_groups region_network_firewall_policies + region_network_policies region_notification_endpoints region_operations regions diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py index 62494524c1d5..bd5b2a60e7ee 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py @@ -86,6 +86,7 @@ from .services.region_disks import RegionDisksClient from .services.region_health_check_services import RegionHealthCheckServicesClient from .services.region_health_checks import RegionHealthChecksClient +from .services.region_health_sources import RegionHealthSourcesClient from .services.region_instance_group_manager_resize_requests import ( RegionInstanceGroupManagerResizeRequestsClient, ) @@ -99,6 +100,7 @@ from .services.region_network_firewall_policies import ( RegionNetworkFirewallPoliciesClient, ) +from .services.region_network_policies import RegionNetworkPoliciesClient from .services.region_notification_endpoints import RegionNotificationEndpointsClient from .services.region_operations import RegionOperationsClient from .services.region_security_policies import RegionSecurityPoliciesClient @@ -156,6 +158,7 @@ AddAssociationNetworkFirewallPolicyRequest, AddAssociationOrganizationSecurityPolicyRequest, AddAssociationRegionNetworkFirewallPolicyRequest, + AddAssociationRegionNetworkPolicyRequest, AddHealthCheckTargetPoolRequest, AddInstancesInstanceGroupRequest, AddInstanceTargetPoolRequest, @@ -179,6 +182,7 @@ AddRuleSecurityPolicyRequest, AddSignedUrlKeyBackendBucketRequest, AddSignedUrlKeyBackendServiceRequest, + AddTrafficClassificationRuleRegionNetworkPolicyRequest, AdvancedMachineFeatures, AggregatedListAcceleratorTypesRequest, AggregatedListAddressesRequest, @@ -207,6 +211,8 @@ AggregatedListPacketMirroringsRequest, AggregatedListPublicDelegatedPrefixesRequest, AggregatedListRegionCommitmentsRequest, + AggregatedListRegionHealthSourcesRequest, + AggregatedListRegionNetworkPoliciesRequest, AggregatedListReservationsRequest, AggregatedListResourcePoliciesRequest, AggregatedListRoutersRequest, @@ -418,6 +424,7 @@ DeleteRegionDiskRequest, DeleteRegionHealthCheckRequest, DeleteRegionHealthCheckServiceRequest, + DeleteRegionHealthSourceRequest, DeleteRegionInstanceGroupManagerRequest, DeleteRegionInstanceGroupManagerResizeRequestRequest, DeleteRegionInstanceTemplateRequest, @@ -425,6 +432,7 @@ DeleteRegionMultiMigRequest, DeleteRegionNetworkEndpointGroupRequest, DeleteRegionNetworkFirewallPolicyRequest, + DeleteRegionNetworkPolicyRequest, DeleteRegionNotificationEndpointRequest, DeleteRegionOperationRequest, DeleteRegionOperationResponse, @@ -562,6 +570,7 @@ GetAssociationNetworkFirewallPolicyRequest, GetAssociationOrganizationSecurityPolicyRequest, GetAssociationRegionNetworkFirewallPolicyRequest, + GetAssociationRegionNetworkPolicyRequest, GetAutoscalerRequest, GetBackendBucketRequest, GetBackendServiceRequest, @@ -668,6 +677,7 @@ GetRegionDiskTypeRequest, GetRegionHealthCheckRequest, GetRegionHealthCheckServiceRequest, + GetRegionHealthSourceRequest, GetRegionInstanceGroupManagerRequest, GetRegionInstanceGroupManagerResizeRequestRequest, GetRegionInstanceGroupRequest, @@ -676,6 +686,7 @@ GetRegionMultiMigRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, + GetRegionNetworkPolicyRequest, GetRegionNotificationEndpointRequest, GetRegionOperationRequest, GetRegionRequest, @@ -724,6 +735,7 @@ GetTargetSslProxyRequest, GetTargetTcpProxyRequest, GetTargetVpnGatewayRequest, + GetTrafficClassificationRuleRegionNetworkPolicyRequest, GetUrlMapRequest, GetVpnGatewayRequest, GetVpnTunnelRequest, @@ -754,6 +766,10 @@ HealthCheckServiceReference, HealthCheckServicesList, HealthChecksScopedList, + HealthSource, + HealthSourceAggregatedList, + HealthSourceList, + HealthSourcesScopedList, HealthStatus, HealthStatusForNetworkEndpoint, Help, @@ -778,6 +794,7 @@ Image, ImageFamilyView, ImageList, + ImageParams, InitialStateConfig, InsertAddressRequest, InsertAutoscalerRequest, @@ -825,6 +842,7 @@ InsertRegionDiskRequest, InsertRegionHealthCheckRequest, InsertRegionHealthCheckServiceRequest, + InsertRegionHealthSourceRequest, InsertRegionInstanceGroupManagerRequest, InsertRegionInstanceGroupManagerResizeRequestRequest, InsertRegionInstanceTemplateRequest, @@ -832,6 +850,7 @@ InsertRegionMultiMigRequest, InsertRegionNetworkEndpointGroupRequest, InsertRegionNetworkFirewallPolicyRequest, + InsertRegionNetworkPolicyRequest, InsertRegionNotificationEndpointRequest, InsertRegionSecurityPolicyRequest, InsertRegionSnapshotRequest, @@ -1122,6 +1141,7 @@ ListRegionDiskTypesRequest, ListRegionHealthCheckServicesRequest, ListRegionHealthChecksRequest, + ListRegionHealthSourcesRequest, ListRegionInstanceGroupManagerResizeRequestsRequest, ListRegionInstanceGroupManagersRequest, ListRegionInstanceGroupsRequest, @@ -1130,6 +1150,7 @@ ListRegionMultiMigsRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, + ListRegionNetworkPoliciesRequest, ListRegionNotificationEndpointsRequest, ListRegionOperationsRequest, ListRegionSecurityPoliciesRequest, @@ -1249,6 +1270,16 @@ NetworkPeeringConnectionStatusConsensusState, NetworkPeeringConnectionStatusTrafficConfiguration, NetworkPerformanceConfig, + NetworkPoliciesScopedList, + NetworkPolicy, + NetworkPolicyAggregatedList, + NetworkPolicyAssociation, + NetworkPolicyList, + NetworkPolicyTrafficClassificationRule, + NetworkPolicyTrafficClassificationRuleAction, + NetworkPolicyTrafficClassificationRuleMatcher, + NetworkPolicyTrafficClassificationRuleMatcherLayer4Config, + NetworkPolicyTrafficClassificationRuleSecureTag, NetworkProfile, NetworkProfileLocation, NetworkProfileNetworkFeatures, @@ -1343,8 +1374,10 @@ PatchRegionDiskSettingRequest, PatchRegionHealthCheckRequest, PatchRegionHealthCheckServiceRequest, + PatchRegionHealthSourceRequest, PatchRegionInstanceGroupManagerRequest, PatchRegionNetworkFirewallPolicyRequest, + PatchRegionNetworkPolicyRequest, PatchRegionSecurityPolicyRequest, PatchRegionSnapshotSettingRequest, PatchRegionSslPolicyRequest, @@ -1367,6 +1400,7 @@ PatchTargetGrpcProxyRequest, PatchTargetHttpProxyRequest, PatchTargetHttpsProxyRequest, + PatchTrafficClassificationRuleRegionNetworkPolicyRequest, PatchUrlMapRequest, PatchWireGroupRequest, PathMatcher, @@ -1460,6 +1494,7 @@ RemoveAssociationNetworkFirewallPolicyRequest, RemoveAssociationOrganizationSecurityPolicyRequest, RemoveAssociationRegionNetworkFirewallPolicyRequest, + RemoveAssociationRegionNetworkPolicyRequest, RemoveHealthCheckTargetPoolRequest, RemoveInstancesInstanceGroupRequest, RemoveInstanceTargetPoolRequest, @@ -1475,6 +1510,8 @@ RemoveRuleRegionNetworkFirewallPolicyRequest, RemoveRuleRegionSecurityPolicyRequest, RemoveRuleSecurityPolicyRequest, + RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, + ReportFaultyReservationSubBlockRequest, ReportHostAsFaultyInstanceRequest, RequestMirrorPolicy, RequestRemovePeeringNetworkRequest, @@ -1499,6 +1536,8 @@ ReservationSubBlockPhysicalTopology, ReservationSubBlocksGetResponse, ReservationSubBlocksListResponse, + ReservationSubBlocksReportFaultyRequest, + ReservationSubBlocksReportFaultyRequestFaultReason, ResetInstanceRequest, ResizeAdvancedInstanceGroupManagerRequest, ResizeAdvancedRegionInstanceGroupManagerRequest, @@ -1745,6 +1784,7 @@ Snapshot, SnapshotAggregatedList, SnapshotList, + SnapshotParams, SnapshotSettings, SnapshotSettingsAccessLocation, SnapshotSettingsAccessLocationAccessLocationPreference, @@ -1899,6 +1939,7 @@ TestIamPermissionsRegionDiskRequest, TestIamPermissionsRegionHealthCheckRequest, TestIamPermissionsRegionHealthCheckServiceRequest, + TestIamPermissionsRegionHealthSourceRequest, TestIamPermissionsRegionInstanceGroupManagerRequest, TestIamPermissionsRegionInstanceGroupRequest, TestIamPermissionsRegionInstantSnapshotRequest, @@ -2052,6 +2093,7 @@ "AddAssociationNetworkFirewallPolicyRequest", "AddAssociationOrganizationSecurityPolicyRequest", "AddAssociationRegionNetworkFirewallPolicyRequest", + "AddAssociationRegionNetworkPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstanceTargetPoolRequest", "AddInstancesInstanceGroupRequest", @@ -2071,6 +2113,7 @@ "AddRuleSecurityPolicyRequest", "AddSignedUrlKeyBackendBucketRequest", "AddSignedUrlKeyBackendServiceRequest", + "AddTrafficClassificationRuleRegionNetworkPolicyRequest", "Address", "AddressAggregatedList", "AddressList", @@ -2105,6 +2148,8 @@ "AggregatedListPacketMirroringsRequest", "AggregatedListPublicDelegatedPrefixesRequest", "AggregatedListRegionCommitmentsRequest", + "AggregatedListRegionHealthSourcesRequest", + "AggregatedListRegionNetworkPoliciesRequest", "AggregatedListReservationsRequest", "AggregatedListResourcePoliciesRequest", "AggregatedListRoutersRequest", @@ -2319,6 +2364,7 @@ "DeleteRegionDiskRequest", "DeleteRegionHealthCheckRequest", "DeleteRegionHealthCheckServiceRequest", + "DeleteRegionHealthSourceRequest", "DeleteRegionInstanceGroupManagerRequest", "DeleteRegionInstanceGroupManagerResizeRequestRequest", "DeleteRegionInstanceTemplateRequest", @@ -2326,6 +2372,7 @@ "DeleteRegionMultiMigRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", + "DeleteRegionNetworkPolicyRequest", "DeleteRegionNotificationEndpointRequest", "DeleteRegionOperationRequest", "DeleteRegionOperationResponse", @@ -2473,6 +2520,7 @@ "GetAssociationNetworkFirewallPolicyRequest", "GetAssociationOrganizationSecurityPolicyRequest", "GetAssociationRegionNetworkFirewallPolicyRequest", + "GetAssociationRegionNetworkPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", "GetBackendServiceRequest", @@ -2579,6 +2627,7 @@ "GetRegionDiskTypeRequest", "GetRegionHealthCheckRequest", "GetRegionHealthCheckServiceRequest", + "GetRegionHealthSourceRequest", "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupManagerResizeRequestRequest", "GetRegionInstanceGroupRequest", @@ -2587,6 +2636,7 @@ "GetRegionMultiMigRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", + "GetRegionNetworkPolicyRequest", "GetRegionNotificationEndpointRequest", "GetRegionOperationRequest", "GetRegionRequest", @@ -2635,6 +2685,7 @@ "GetTargetSslProxyRequest", "GetTargetTcpProxyRequest", "GetTargetVpnGatewayRequest", + "GetTrafficClassificationRuleRegionNetworkPolicyRequest", "GetUrlMapRequest", "GetVpnGatewayRequest", "GetVpnTunnelRequest", @@ -2673,6 +2724,10 @@ "HealthChecksAggregatedList", "HealthChecksClient", "HealthChecksScopedList", + "HealthSource", + "HealthSourceAggregatedList", + "HealthSourceList", + "HealthSourcesScopedList", "HealthStatus", "HealthStatusForNetworkEndpoint", "Help", @@ -2695,6 +2750,7 @@ "ImageFamilyView", "ImageFamilyViewsClient", "ImageList", + "ImageParams", "ImagesClient", "InitialStateConfig", "InsertAddressRequest", @@ -2743,6 +2799,7 @@ "InsertRegionDiskRequest", "InsertRegionHealthCheckRequest", "InsertRegionHealthCheckServiceRequest", + "InsertRegionHealthSourceRequest", "InsertRegionInstanceGroupManagerRequest", "InsertRegionInstanceGroupManagerResizeRequestRequest", "InsertRegionInstanceTemplateRequest", @@ -2750,6 +2807,7 @@ "InsertRegionMultiMigRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", + "InsertRegionNetworkPolicyRequest", "InsertRegionNotificationEndpointRequest", "InsertRegionSecurityPolicyRequest", "InsertRegionSnapshotRequest", @@ -3055,6 +3113,7 @@ "ListRegionDisksRequest", "ListRegionHealthCheckServicesRequest", "ListRegionHealthChecksRequest", + "ListRegionHealthSourcesRequest", "ListRegionInstanceGroupManagerResizeRequestsRequest", "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", @@ -3063,6 +3122,7 @@ "ListRegionMultiMigsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", + "ListRegionNetworkPoliciesRequest", "ListRegionNotificationEndpointsRequest", "ListRegionOperationsRequest", "ListRegionSecurityPoliciesRequest", @@ -3188,6 +3248,16 @@ "NetworkPeeringConnectionStatusConsensusState", "NetworkPeeringConnectionStatusTrafficConfiguration", "NetworkPerformanceConfig", + "NetworkPoliciesScopedList", + "NetworkPolicy", + "NetworkPolicyAggregatedList", + "NetworkPolicyAssociation", + "NetworkPolicyList", + "NetworkPolicyTrafficClassificationRule", + "NetworkPolicyTrafficClassificationRuleAction", + "NetworkPolicyTrafficClassificationRuleMatcher", + "NetworkPolicyTrafficClassificationRuleMatcherLayer4Config", + "NetworkPolicyTrafficClassificationRuleSecureTag", "NetworkProfile", "NetworkProfileLocation", "NetworkProfileNetworkFeatures", @@ -3289,8 +3359,10 @@ "PatchRegionDiskSettingRequest", "PatchRegionHealthCheckRequest", "PatchRegionHealthCheckServiceRequest", + "PatchRegionHealthSourceRequest", "PatchRegionInstanceGroupManagerRequest", "PatchRegionNetworkFirewallPolicyRequest", + "PatchRegionNetworkPolicyRequest", "PatchRegionSecurityPolicyRequest", "PatchRegionSnapshotSettingRequest", "PatchRegionSslPolicyRequest", @@ -3313,6 +3385,7 @@ "PatchTargetGrpcProxyRequest", "PatchTargetHttpProxyRequest", "PatchTargetHttpsProxyRequest", + "PatchTrafficClassificationRuleRegionNetworkPolicyRequest", "PatchUrlMapRequest", "PatchWireGroupRequest", "PathMatcher", @@ -3380,6 +3453,7 @@ "RegionDisksStartAsyncReplicationRequest", "RegionHealthCheckServicesClient", "RegionHealthChecksClient", + "RegionHealthSourcesClient", "RegionInstanceGroupList", "RegionInstanceGroupManagerDeleteInstanceConfigReq", "RegionInstanceGroupManagerList", @@ -3419,6 +3493,7 @@ "RegionNetworkFirewallPoliciesClient", "RegionNetworkFirewallPoliciesGetEffectiveFirewallsResponse", "RegionNetworkFirewallPoliciesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", + "RegionNetworkPoliciesClient", "RegionNotificationEndpointsClient", "RegionOperationsClient", "RegionSecurityPoliciesClient", @@ -3440,6 +3515,7 @@ "RemoveAssociationNetworkFirewallPolicyRequest", "RemoveAssociationOrganizationSecurityPolicyRequest", "RemoveAssociationRegionNetworkFirewallPolicyRequest", + "RemoveAssociationRegionNetworkPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstanceTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", @@ -3455,6 +3531,8 @@ "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "RemoveTrafficClassificationRuleRegionNetworkPolicyRequest", + "ReportFaultyReservationSubBlockRequest", "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "RequestRemovePeeringNetworkRequest", @@ -3477,6 +3555,8 @@ "ReservationSubBlocksClient", "ReservationSubBlocksGetResponse", "ReservationSubBlocksListResponse", + "ReservationSubBlocksReportFaultyRequest", + "ReservationSubBlocksReportFaultyRequestFaultReason", "ReservationsBlocksPerformMaintenanceRequest", "ReservationsClient", "ReservationsPerformMaintenanceRequest", @@ -3734,6 +3814,7 @@ "Snapshot", "SnapshotAggregatedList", "SnapshotList", + "SnapshotParams", "SnapshotSettings", "SnapshotSettingsAccessLocation", "SnapshotSettingsAccessLocationAccessLocationPreference", @@ -3902,6 +3983,7 @@ "TestIamPermissionsRegionDiskRequest", "TestIamPermissionsRegionHealthCheckRequest", "TestIamPermissionsRegionHealthCheckServiceRequest", + "TestIamPermissionsRegionHealthSourceRequest", "TestIamPermissionsRegionInstanceGroupManagerRequest", "TestIamPermissionsRegionInstanceGroupRequest", "TestIamPermissionsRegionInstantSnapshotRequest", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json index 81797f34a269..3e84ca8ad475 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json @@ -3406,6 +3406,50 @@ } } }, + "RegionHealthSources": { + "clients": { + "rest": { + "libraryClient": "RegionHealthSourcesClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, "RegionInstanceGroupManagerResizeRequests": { "clients": { "rest": { @@ -3882,6 +3926,80 @@ } } }, + "RegionNetworkPolicies": { + "clients": { + "rest": { + "libraryClient": "RegionNetworkPoliciesClient", + "rpcs": { + "AddAssociation": { + "methods": [ + "add_association" + ] + }, + "AddTrafficClassificationRule": { + "methods": [ + "add_traffic_classification_rule" + ] + }, + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetAssociation": { + "methods": [ + "get_association" + ] + }, + "GetTrafficClassificationRule": { + "methods": [ + "get_traffic_classification_rule" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "PatchTrafficClassificationRule": { + "methods": [ + "patch_traffic_classification_rule" + ] + }, + "RemoveAssociation": { + "methods": [ + "remove_association" + ] + }, + "RemoveTrafficClassificationRule": { + "methods": [ + "remove_traffic_classification_rule" + ] + } + } + } + } + }, "RegionNotificationEndpoints": { "clients": { "rest": { @@ -4402,6 +4520,11 @@ "methods": [ "perform_maintenance" ] + }, + "ReportFaulty": { + "methods": [ + "report_faulty" + ] } } } diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/__init__.py new file mode 100644 index 000000000000..66c302d62c90 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 RegionHealthSourcesClient + +__all__ = ("RegionHealthSourcesClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/client.py new file mode 100644 index 000000000000..b903ed2a7e4a --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/client.py @@ -0,0 +1,2185 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +import functools +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +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 +import google.protobuf + +from google.cloud.compute_v1beta 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__) + +from google.api_core import extended_operation # type: ignore + +from google.cloud.compute_v1beta.services.region_health_sources import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, RegionHealthSourcesTransport +from .transports.rest import RegionHealthSourcesRestTransport + + +class RegionHealthSourcesClientMeta(type): + """Metaclass for the RegionHealthSources 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[RegionHealthSourcesTransport]] + _transport_registry["rest"] = RegionHealthSourcesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RegionHealthSourcesTransport]: + """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 RegionHealthSourcesClient(metaclass=RegionHealthSourcesClientMeta): + """The RegionHealthSources API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """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: + 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) + 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" + + @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: + RegionHealthSourcesClient: 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: + RegionHealthSourcesClient: 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) -> RegionHealthSourcesTransport: + """Returns the transport used by the client instance. + + Returns: + RegionHealthSourcesTransport: 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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true": + 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 = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true", 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 + ): + """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 = RegionHealthSourcesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = RegionHealthSourcesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RegionHealthSourcesClient._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 = RegionHealthSourcesClient._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): + """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, + RegionHealthSourcesTransport, + Callable[..., RegionHealthSourcesTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the region health sources 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,RegionHealthSourcesTransport,Callable[..., RegionHealthSourcesTransport]]]): + 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 RegionHealthSourcesTransport 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, + ) = RegionHealthSourcesClient._read_environment_variables() + self._client_cert_source = RegionHealthSourcesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RegionHealthSourcesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # 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, RegionHealthSourcesTransport) + if transport_provided: + # transport is a RegionHealthSourcesTransport 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(RegionHealthSourcesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or RegionHealthSourcesClient._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[RegionHealthSourcesTransport], + Callable[..., RegionHealthSourcesTransport], + ] = ( + RegionHealthSourcesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RegionHealthSourcesTransport], 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_v1beta.RegionHealthSourcesClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "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.v1beta.RegionHealthSources", + "credentialsType": None, + }, + ) + + def aggregated_list( + self, + request: Optional[ + Union[compute.AggregatedListRegionHealthSourcesRequest, 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 HealthSource resources (all regional) + available to the specified project. To prevent failure, Google + recommends 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_v1beta + + def sample_aggregated_list(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.AggregatedListRegionHealthSourcesRequest( + 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_v1beta.types.AggregatedListRegionHealthSourcesRequest, dict]): + The request object. A request message for + RegionHealthSources.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_v1beta.services.region_health_sources.pagers.AggregatedListPager: + Contains a list of + HealthSourcesScopedList. + 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.AggregatedListRegionHealthSourcesRequest): + request = compute.AggregatedListRegionHealthSourcesRequest(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.DeleteRegionHealthSourceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + health_source: 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 the specified HealthSource in the given + region + + .. 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_v1beta + + def sample_delete(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteRegionHealthSourceRequest( + health_source="health_source_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.DeleteRegionHealthSourceRequest, dict]): + The request object. A request message for + RegionHealthSources.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. + region (str): + Name of the region scoping this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source (str): + Name of the HealthSource resource to + delete. + + This corresponds to the ``health_source`` 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, region, health_source] + 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.DeleteRegionHealthSourceRequest): + request = compute.DeleteRegionHealthSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if health_source is not None: + request.health_source = health_source + + # 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), + ("region", request.region), + ("health_source", request.health_source), + ) + ), + ) + + # 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.DeleteRegionHealthSourceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + health_source: 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 the specified HealthSource in the given + region + + .. 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_v1beta + + def sample_delete(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteRegionHealthSourceRequest( + health_source="health_source_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.DeleteRegionHealthSourceRequest, dict]): + The request object. A request message for + RegionHealthSources.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. + region (str): + Name of the region scoping this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source (str): + Name of the HealthSource resource to + delete. + + This corresponds to the ``health_source`` 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, region, health_source] + 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.DeleteRegionHealthSourceRequest): + request = compute.DeleteRegionHealthSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if health_source is not None: + request.health_source = health_source + + # 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), + ("region", request.region), + ("health_source", request.health_source), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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.GetRegionHealthSourceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + health_source: 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.HealthSource: + r"""Returns the specified HealthSource resource in the + given region. + + .. 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_v1beta + + def sample_get(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetRegionHealthSourceRequest( + health_source="health_source_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetRegionHealthSourceRequest, dict]): + The request object. A request message for + RegionHealthSources.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. + region (str): + Name of the region scoping this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source (str): + Name of the HealthSource resource to + return. + + This corresponds to the ``health_source`` 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_v1beta.types.HealthSource: + Represents a health source. A health + source resource specifies the source + resources and the health aggregation + policy applied to the source resources + to determine the aggregated health + status. + + """ + # 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, region, health_source] + 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.GetRegionHealthSourceRequest): + request = compute.GetRegionHealthSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if health_source is not None: + request.health_source = health_source + + # 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), + ("region", request.region), + ("health_source", request.health_source), + ) + ), + ) + + # 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.InsertRegionHealthSourceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + health_source_resource: Optional[compute.HealthSource] = 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"""Create a HealthSource in the specified project in the + given region using the parameters that are included in + the request. + + .. 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_v1beta + + def sample_insert(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertRegionHealthSourceRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.InsertRegionHealthSourceRequest, dict]): + The request object. A request message for + RegionHealthSources.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. + region (str): + Name of the region scoping this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source_resource (google.cloud.compute_v1beta.types.HealthSource): + The body resource for this request + This corresponds to the ``health_source_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, region, health_source_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.InsertRegionHealthSourceRequest): + request = compute.InsertRegionHealthSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if health_source_resource is not None: + request.health_source_resource = health_source_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), + ("region", request.region), + ) + ), + ) + + # 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.InsertRegionHealthSourceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + health_source_resource: Optional[compute.HealthSource] = 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"""Create a HealthSource in the specified project in the + given region using the parameters that are included in + the request. + + .. 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_v1beta + + def sample_insert(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertRegionHealthSourceRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.InsertRegionHealthSourceRequest, dict]): + The request object. A request message for + RegionHealthSources.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. + region (str): + Name of the region scoping this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source_resource (google.cloud.compute_v1beta.types.HealthSource): + The body resource for this request + This corresponds to the ``health_source_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, region, health_source_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.InsertRegionHealthSourceRequest): + request = compute.InsertRegionHealthSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if health_source_resource is not None: + request.health_source_resource = health_source_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), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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.ListRegionHealthSourcesRequest, dict]] = None, + *, + project: Optional[str] = None, + region: 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 the HealthSources for a project in the given + region. + + .. 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_v1beta + + def sample_list(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.ListRegionHealthSourcesRequest( + project="project_value", + region="region_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_v1beta.types.ListRegionHealthSourcesRequest, dict]): + The request object. A request message for + RegionHealthSources.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. + region (str): + Name of the region scoping this + request. + + This corresponds to the ``region`` 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_v1beta.services.region_health_sources.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, region] + 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.ListRegionHealthSourcesRequest): + request = compute.ListRegionHealthSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + + # 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), + ("region", request.region), + ) + ), + ) + + # 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 patch_unary( + self, + request: Optional[Union[compute.PatchRegionHealthSourceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + health_source: Optional[str] = None, + health_source_resource: Optional[compute.HealthSource] = 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 the specified regional HealthSource resource + with the data included in the request. This method + supports PATCH semantics and uses the JSON merge patch + format and processing rules. + + .. 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_v1beta + + def sample_patch(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchRegionHealthSourceRequest( + health_source="health_source_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PatchRegionHealthSourceRequest, dict]): + The request object. A request message for + RegionHealthSources.Patch. 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. + region (str): + Name of the region scoping this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source (str): + Name of the HealthSource to update. + The name must be 1-63 characters long, + and comply with RFC1035. + + This corresponds to the ``health_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source_resource (google.cloud.compute_v1beta.types.HealthSource): + The body resource for this request + This corresponds to the ``health_source_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, region, health_source, health_source_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.PatchRegionHealthSourceRequest): + request = compute.PatchRegionHealthSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if health_source is not None: + request.health_source = health_source + if health_source_resource is not None: + request.health_source_resource = health_source_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # 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), + ("region", request.region), + ("health_source", request.health_source), + ) + ), + ) + + # 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 patch( + self, + request: Optional[Union[compute.PatchRegionHealthSourceRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + health_source: Optional[str] = None, + health_source_resource: Optional[compute.HealthSource] = 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 the specified regional HealthSource resource + with the data included in the request. This method + supports PATCH semantics and uses the JSON merge patch + format and processing rules. + + .. 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_v1beta + + def sample_patch(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchRegionHealthSourceRequest( + health_source="health_source_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PatchRegionHealthSourceRequest, dict]): + The request object. A request message for + RegionHealthSources.Patch. 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. + region (str): + Name of the region scoping this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source (str): + Name of the HealthSource to update. + The name must be 1-63 characters long, + and comply with RFC1035. + + This corresponds to the ``health_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + health_source_resource (google.cloud.compute_v1beta.types.HealthSource): + The body resource for this request + This corresponds to the ``health_source_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, region, health_source, health_source_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.PatchRegionHealthSourceRequest): + request = compute.PatchRegionHealthSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if health_source is not None: + request.health_source = health_source + if health_source_resource is not None: + request.health_source_resource = health_source_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # 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), + ("region", request.region), + ("health_source", request.health_source), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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 test_iam_permissions( + self, + request: Optional[ + Union[compute.TestIamPermissionsRegionHealthSourceRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource: Optional[str] = None, + test_permissions_request_resource: Optional[ + compute.TestPermissionsRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.TestPermissionsResponse: + r"""Returns permissions that a caller has on the + specified resource. + + .. 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_v1beta + + def sample_test_iam_permissions(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.TestIamPermissionsRegionHealthSourceRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.TestIamPermissionsRegionHealthSourceRequest, dict]): + The request object. A request message for + RegionHealthSources.TestIamPermissions. + 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. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` 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. + test_permissions_request_resource (google.cloud.compute_v1beta.types.TestPermissionsRequest): + The body resource for this request + This corresponds to the ``test_permissions_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_v1beta.types.TestPermissionsResponse: + + """ + # 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, + region, + resource, + test_permissions_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.TestIamPermissionsRegionHealthSourceRequest): + request = compute.TestIamPermissionsRegionHealthSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if resource is not None: + request.resource = resource + if test_permissions_request_resource is not None: + request.test_permissions_request_resource = ( + test_permissions_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # 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), + ("region", request.region), + ("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 __enter__(self) -> "RegionHealthSourcesClient": + 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__ = ("RegionHealthSourcesClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/pagers.py new file mode 100644 index 000000000000..ad16f88a1dc8 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/pagers.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_v1beta.types import compute + + +class AggregatedListPager: + """A pager for iterating through ``aggregated_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1beta.types.HealthSourceAggregatedList` 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_v1beta.types.HealthSourceAggregatedList` + 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.HealthSourceAggregatedList], + request: compute.AggregatedListRegionHealthSourcesRequest, + response: compute.HealthSourceAggregatedList, + *, + 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_v1beta.types.AggregatedListRegionHealthSourcesRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.HealthSourceAggregatedList): + 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.AggregatedListRegionHealthSourcesRequest(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.HealthSourceAggregatedList]: + 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.HealthSourcesScopedList]]: + for page in self.pages: + yield from page.items.items() + + def get(self, key: str) -> Optional[compute.HealthSourcesScopedList]: + 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_v1beta.types.HealthSourceList` 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_v1beta.types.HealthSourceList` + 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.HealthSourceList], + request: compute.ListRegionHealthSourcesRequest, + response: compute.HealthSourceList, + *, + 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_v1beta.types.ListRegionHealthSourcesRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.HealthSourceList): + 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.ListRegionHealthSourcesRequest(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.HealthSourceList]: + 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.HealthSource]: + 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-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/README.rst new file mode 100644 index 000000000000..8365e0728465 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RegionHealthSourcesTransport` is the ABC for all transports. +- public child `RegionHealthSourcesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RegionHealthSourcesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRegionHealthSourcesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RegionHealthSourcesRestTransport` 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-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/__init__.py new file mode 100644 index 000000000000..b1c0d0e70377 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 RegionHealthSourcesTransport +from .rest import RegionHealthSourcesRestInterceptor, RegionHealthSourcesRestTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[RegionHealthSourcesTransport]] +_transport_registry["rest"] = RegionHealthSourcesRestTransport + +__all__ = ( + "RegionHealthSourcesTransport", + "RegionHealthSourcesRestTransport", + "RegionHealthSourcesRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/base.py new file mode 100644 index 000000000000..6de53a41810b --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/base.py @@ -0,0 +1,272 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.compute_v1beta import gapic_version as package_version +from google.cloud.compute_v1beta.services import region_operations +from google.cloud.compute_v1beta.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 RegionHealthSourcesTransport(abc.ABC): + """Abstract transport class for RegionHealthSources.""" + + 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. + """ + self._extended_operations_services: Dict[str, Any] = {} + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # 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_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # 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 + + @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_timeout=None, + client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=None, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_timeout=None, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=None, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_timeout=None, + client_info=client_info, + ), + self.patch: gapic_v1.method.wrap_method( + self.patch, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + 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.AggregatedListRegionHealthSourcesRequest], + Union[ + compute.HealthSourceAggregatedList, + Awaitable[compute.HealthSourceAggregatedList], + ], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteRegionHealthSourceRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetRegionHealthSourceRequest], + Union[compute.HealthSource, Awaitable[compute.HealthSource]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertRegionHealthSourceRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListRegionHealthSourcesRequest], + Union[compute.HealthSourceList, Awaitable[compute.HealthSourceList]], + ]: + raise NotImplementedError() + + @property + def patch( + self, + ) -> Callable[ + [compute.PatchRegionHealthSourceRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [compute.TestIamPermissionsRegionHealthSourceRequest], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _region_operations_client(self) -> region_operations.RegionOperationsClient: + ex_op_service = self._extended_operations_services.get("region_operations") + if not ex_op_service: + ex_op_service = region_operations.RegionOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["region_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("RegionHealthSourcesTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/rest.py new file mode 100644 index 000000000000..267369c2aecc --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/rest.py @@ -0,0 +1,1746 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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 +import google.protobuf +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1beta.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseRegionHealthSourcesRestTransport + +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 RegionHealthSourcesRestInterceptor: + """Interceptor for RegionHealthSources. + + 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 RegionHealthSourcesRestTransport. + + .. code-block:: python + class MyCustomRegionHealthSourcesInterceptor(RegionHealthSourcesRestInterceptor): + 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_patch(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_patch(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 + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegionHealthSourcesRestTransport(interceptor=MyCustomRegionHealthSourcesInterceptor()) + client = RegionHealthSourcesClient(transport=transport) + + + """ + + def pre_aggregated_list( + self, + request: compute.AggregatedListRegionHealthSourcesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.AggregatedListRegionHealthSourcesRequest, + 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 RegionHealthSources server. + """ + return request, metadata + + def post_aggregated_list( + self, response: compute.HealthSourceAggregatedList + ) -> compute.HealthSourceAggregatedList: + """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 RegionHealthSources 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.HealthSourceAggregatedList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.HealthSourceAggregatedList, 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 RegionHealthSources 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.DeleteRegionHealthSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.DeleteRegionHealthSourceRequest, 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 RegionHealthSources 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 RegionHealthSources 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 RegionHealthSources 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.GetRegionHealthSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetRegionHealthSourceRequest, 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 RegionHealthSources server. + """ + return request, metadata + + def post_get(self, response: compute.HealthSource) -> compute.HealthSource: + """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 RegionHealthSources 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.HealthSource, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.HealthSource, 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 RegionHealthSources 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.InsertRegionHealthSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.InsertRegionHealthSourceRequest, 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 RegionHealthSources 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 RegionHealthSources 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 RegionHealthSources 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.ListRegionHealthSourcesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListRegionHealthSourcesRequest, 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 RegionHealthSources server. + """ + return request, metadata + + def post_list(self, response: compute.HealthSourceList) -> compute.HealthSourceList: + """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 RegionHealthSources 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.HealthSourceList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.HealthSourceList, 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 RegionHealthSources 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_patch( + self, + request: compute.PatchRegionHealthSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.PatchRegionHealthSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for patch + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionHealthSources server. + """ + return request, metadata + + def post_patch(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for patch + + DEPRECATED. Please use the `post_patch_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionHealthSources server but before + it is returned to user code. This `post_patch` interceptor runs + before the `post_patch_with_metadata` interceptor. + """ + return response + + def post_patch_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 patch + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionHealthSources server but before it is returned to user code. + + We recommend only using this `post_patch_with_metadata` + interceptor in new development instead of the `post_patch` interceptor. + When both interceptors are used, this `post_patch_with_metadata` interceptor runs after the + `post_patch` interceptor. The (possibly modified) response returned by + `post_patch` will be passed to + `post_patch_with_metadata`. + """ + return response, metadata + + def pre_test_iam_permissions( + self, + request: compute.TestIamPermissionsRegionHealthSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.TestIamPermissionsRegionHealthSourceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionHealthSources server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: compute.TestPermissionsResponse + ) -> compute.TestPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + DEPRECATED. Please use the `post_test_iam_permissions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionHealthSources server but before + it is returned to user code. This `post_test_iam_permissions` interceptor runs + before the `post_test_iam_permissions_with_metadata` interceptor. + """ + return response + + def post_test_iam_permissions_with_metadata( + self, + response: compute.TestPermissionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.TestPermissionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionHealthSources server but before it is returned to user code. + + We recommend only using this `post_test_iam_permissions_with_metadata` + interceptor in new development instead of the `post_test_iam_permissions` interceptor. + When both interceptors are used, this `post_test_iam_permissions_with_metadata` interceptor runs after the + `post_test_iam_permissions` interceptor. The (possibly modified) response returned by + `post_test_iam_permissions` will be passed to + `post_test_iam_permissions_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class RegionHealthSourcesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionHealthSourcesRestInterceptor + + +class RegionHealthSourcesRestTransport(_BaseRegionHealthSourcesRestTransport): + """REST backend synchronous transport for RegionHealthSources. + + The RegionHealthSources 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[RegionHealthSourcesRestInterceptor] = 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. + """ + # 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 RegionHealthSourcesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AggregatedList( + _BaseRegionHealthSourcesRestTransport._BaseAggregatedList, + RegionHealthSourcesRestStub, + ): + def __hash__(self): + return hash("RegionHealthSourcesRestTransport.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.AggregatedListRegionHealthSourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.HealthSourceAggregatedList: + r"""Call the aggregated list method over HTTP. + + Args: + request (~.compute.AggregatedListRegionHealthSourcesRequest): + The request object. A request message for + RegionHealthSources.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.HealthSourceAggregatedList: + Contains a list of + HealthSourcesScopedList. + + """ + + http_options = ( + _BaseRegionHealthSourcesRestTransport._BaseAggregatedList._get_http_options() + ) + + request, metadata = self._interceptor.pre_aggregated_list(request, metadata) + transcoded_request = _BaseRegionHealthSourcesRestTransport._BaseAggregatedList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionHealthSourcesRestTransport._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_v1beta.RegionHealthSourcesClient.AggregatedList", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "AggregatedList", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionHealthSourcesRestTransport._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.HealthSourceAggregatedList() + pb_resp = compute.HealthSourceAggregatedList.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.HealthSourceAggregatedList.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_v1beta.RegionHealthSourcesClient.aggregated_list", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "AggregatedList", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Delete( + _BaseRegionHealthSourcesRestTransport._BaseDelete, RegionHealthSourcesRestStub + ): + def __hash__(self): + return hash("RegionHealthSourcesRestTransport.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.DeleteRegionHealthSourceRequest, + *, + 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.DeleteRegionHealthSourceRequest): + The request object. A request message for + RegionHealthSources.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, read Handling 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 = ( + _BaseRegionHealthSourcesRestTransport._BaseDelete._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete(request, metadata) + transcoded_request = _BaseRegionHealthSourcesRestTransport._BaseDelete._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionHealthSourcesRestTransport._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_v1beta.RegionHealthSourcesClient.Delete", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "Delete", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionHealthSourcesRestTransport._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_v1beta.RegionHealthSourcesClient.delete", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "Delete", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Get( + _BaseRegionHealthSourcesRestTransport._BaseGet, RegionHealthSourcesRestStub + ): + def __hash__(self): + return hash("RegionHealthSourcesRestTransport.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.GetRegionHealthSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.HealthSource: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetRegionHealthSourceRequest): + The request object. A request message for + RegionHealthSources.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.HealthSource: + Represents a health source. A health + source resource specifies the source + resources and the health aggregation + policy applied to the source resources + to determine the aggregated health + status. + + """ + + http_options = ( + _BaseRegionHealthSourcesRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseRegionHealthSourcesRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRegionHealthSourcesRestTransport._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_v1beta.RegionHealthSourcesClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionHealthSourcesRestTransport._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.HealthSource() + pb_resp = compute.HealthSource.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.HealthSource.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_v1beta.RegionHealthSourcesClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Insert( + _BaseRegionHealthSourcesRestTransport._BaseInsert, RegionHealthSourcesRestStub + ): + def __hash__(self): + return hash("RegionHealthSourcesRestTransport.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.InsertRegionHealthSourceRequest, + *, + 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.InsertRegionHealthSourceRequest): + The request object. A request message for + RegionHealthSources.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, read Handling 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 = ( + _BaseRegionHealthSourcesRestTransport._BaseInsert._get_http_options() + ) + + request, metadata = self._interceptor.pre_insert(request, metadata) + transcoded_request = _BaseRegionHealthSourcesRestTransport._BaseInsert._get_transcoded_request( + http_options, request + ) + + body = _BaseRegionHealthSourcesRestTransport._BaseInsert._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRegionHealthSourcesRestTransport._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_v1beta.RegionHealthSourcesClient.Insert", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "Insert", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionHealthSourcesRestTransport._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_v1beta.RegionHealthSourcesClient.insert", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "Insert", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List( + _BaseRegionHealthSourcesRestTransport._BaseList, RegionHealthSourcesRestStub + ): + def __hash__(self): + return hash("RegionHealthSourcesRestTransport.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.ListRegionHealthSourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.HealthSourceList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListRegionHealthSourcesRequest): + The request object. A request message for + RegionHealthSources.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.HealthSourceList: + + """ + + http_options = ( + _BaseRegionHealthSourcesRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = ( + _BaseRegionHealthSourcesRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRegionHealthSourcesRestTransport._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_v1beta.RegionHealthSourcesClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionHealthSourcesRestTransport._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.HealthSourceList() + pb_resp = compute.HealthSourceList.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.HealthSourceList.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_v1beta.RegionHealthSourcesClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Patch( + _BaseRegionHealthSourcesRestTransport._BasePatch, RegionHealthSourcesRestStub + ): + def __hash__(self): + return hash("RegionHealthSourcesRestTransport.Patch") + + @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.PatchRegionHealthSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the patch method over HTTP. + + Args: + request (~.compute.PatchRegionHealthSourceRequest): + The request object. A request message for + RegionHealthSources.Patch. 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, read Handling 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 = ( + _BaseRegionHealthSourcesRestTransport._BasePatch._get_http_options() + ) + + request, metadata = self._interceptor.pre_patch(request, metadata) + transcoded_request = _BaseRegionHealthSourcesRestTransport._BasePatch._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseRegionHealthSourcesRestTransport._BasePatch._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRegionHealthSourcesRestTransport._BasePatch._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_v1beta.RegionHealthSourcesClient.Patch", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "Patch", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionHealthSourcesRestTransport._Patch._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_patch(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_patch_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_v1beta.RegionHealthSourcesClient.patch", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "Patch", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _TestIamPermissions( + _BaseRegionHealthSourcesRestTransport._BaseTestIamPermissions, + RegionHealthSourcesRestStub, + ): + def __hash__(self): + return hash("RegionHealthSourcesRestTransport.TestIamPermissions") + + @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.TestIamPermissionsRegionHealthSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.TestPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (~.compute.TestIamPermissionsRegionHealthSourceRequest): + The request object. A request message for + RegionHealthSources.TestIamPermissions. + 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.TestPermissionsResponse: + + """ + + http_options = ( + _BaseRegionHealthSourcesRestTransport._BaseTestIamPermissions._get_http_options() + ) + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseRegionHealthSourcesRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseRegionHealthSourcesRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRegionHealthSourcesRestTransport._BaseTestIamPermissions._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_v1beta.RegionHealthSourcesClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + RegionHealthSourcesRestTransport._TestIamPermissions._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.TestPermissionsResponse() + pb_resp = compute.TestPermissionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_test_iam_permissions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_test_iam_permissions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.TestPermissionsResponse.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_v1beta.RegionHealthSourcesClient.test_iam_permissions", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionHealthSources", + "rpcName": "TestIamPermissions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListRegionHealthSourcesRequest], + compute.HealthSourceAggregatedList, + ]: + # 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.DeleteRegionHealthSourceRequest], 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.GetRegionHealthSourceRequest], compute.HealthSource]: + # 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.InsertRegionHealthSourceRequest], 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.ListRegionHealthSourcesRequest], compute.HealthSourceList]: + # 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 patch( + self, + ) -> Callable[[compute.PatchRegionHealthSourceRequest], 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._Patch(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [compute.TestIamPermissionsRegionHealthSourceRequest], + compute.TestPermissionsResponse, + ]: + # 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._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("RegionHealthSourcesRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/rest_base.py new file mode 100644 index 000000000000..377b45f8e9da --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_health_sources/transports/rest_base.py @@ -0,0 +1,443 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_v1beta.types import compute + +from .base import DEFAULT_CLIENT_INFO, RegionHealthSourcesTransport + + +class _BaseRegionHealthSourcesRestTransport(RegionHealthSourcesTransport): + """Base REST backend transport for RegionHealthSources. + + 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/beta/projects/{project}/aggregated/healthSources", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AggregatedListRegionHealthSourcesRequest.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( + _BaseRegionHealthSourcesRestTransport._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": "delete", + "uri": "/compute/beta/projects/{project}/regions/{region}/healthSources/{health_source}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteRegionHealthSourceRequest.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( + _BaseRegionHealthSourcesRestTransport._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/beta/projects/{project}/regions/{region}/healthSources/{health_source}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetRegionHealthSourceRequest.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( + _BaseRegionHealthSourcesRestTransport._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/beta/projects/{project}/regions/{region}/healthSources", + "body": "health_source_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.InsertRegionHealthSourceRequest.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( + _BaseRegionHealthSourcesRestTransport._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/beta/projects/{project}/regions/{region}/healthSources", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListRegionHealthSourcesRequest.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( + _BaseRegionHealthSourcesRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BasePatch: + 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/beta/projects/{project}/regions/{region}/healthSources/{health_source}", + "body": "health_source_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.PatchRegionHealthSourceRequest.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( + _BaseRegionHealthSourcesRestTransport._BasePatch._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseTestIamPermissions: + 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/beta/projects/{project}/regions/{region}/healthSources/{resource}/testIamPermissions", + "body": "test_permissions_request_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.TestIamPermissionsRegionHealthSourceRequest.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( + _BaseRegionHealthSourcesRestTransport._BaseTestIamPermissions._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseRegionHealthSourcesRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/__init__.py new file mode 100644 index 000000000000..1c9e7cca6255 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 RegionNetworkPoliciesClient + +__all__ = ("RegionNetworkPoliciesClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/client.py new file mode 100644 index 000000000000..81895ec0e5d1 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/client.py @@ -0,0 +1,3898 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +import functools +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +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 +import google.protobuf + +from google.cloud.compute_v1beta 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__) + +from google.api_core import extended_operation # type: ignore + +from google.cloud.compute_v1beta.services.region_network_policies import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, RegionNetworkPoliciesTransport +from .transports.rest import RegionNetworkPoliciesRestTransport + + +class RegionNetworkPoliciesClientMeta(type): + """Metaclass for the RegionNetworkPolicies 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[RegionNetworkPoliciesTransport]] + _transport_registry["rest"] = RegionNetworkPoliciesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RegionNetworkPoliciesTransport]: + """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 RegionNetworkPoliciesClient(metaclass=RegionNetworkPoliciesClientMeta): + """The RegionNetworkPolicies API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """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: + 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) + 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" + + @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: + RegionNetworkPoliciesClient: 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: + RegionNetworkPoliciesClient: 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) -> RegionNetworkPoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + RegionNetworkPoliciesTransport: 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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true": + 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 = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true", 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 + ): + """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 = RegionNetworkPoliciesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = RegionNetworkPoliciesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + RegionNetworkPoliciesClient._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 = RegionNetworkPoliciesClient._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): + """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, + RegionNetworkPoliciesTransport, + Callable[..., RegionNetworkPoliciesTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the region network 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,RegionNetworkPoliciesTransport,Callable[..., RegionNetworkPoliciesTransport]]]): + 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 RegionNetworkPoliciesTransport 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, + ) = RegionNetworkPoliciesClient._read_environment_variables() + self._client_cert_source = RegionNetworkPoliciesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RegionNetworkPoliciesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # 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, RegionNetworkPoliciesTransport) + if transport_provided: + # transport is a RegionNetworkPoliciesTransport 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(RegionNetworkPoliciesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or RegionNetworkPoliciesClient._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[RegionNetworkPoliciesTransport], + Callable[..., RegionNetworkPoliciesTransport], + ] = ( + RegionNetworkPoliciesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RegionNetworkPoliciesTransport], 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_v1beta.RegionNetworkPoliciesClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "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.v1beta.RegionNetworkPolicies", + "credentialsType": None, + }, + ) + + def add_association_unary( + self, + request: Optional[ + Union[compute.AddAssociationRegionNetworkPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy: Optional[str] = None, + network_policy_association_resource: Optional[ + compute.NetworkPolicyAssociation + ] = 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"""Inserts an association for the specified network + 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_v1beta + + def sample_add_association(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.AddAssociationRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.add_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.AddAssociationRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.AddAssociation. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_association_resource (google.cloud.compute_v1beta.types.NetworkPolicyAssociation): + The body resource for this request + This corresponds to the ``network_policy_association_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, + region, + network_policy, + network_policy_association_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.AddAssociationRegionNetworkPolicyRequest): + request = compute.AddAssociationRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + if network_policy_association_resource is not None: + request.network_policy_association_resource = ( + network_policy_association_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_association] + + # 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), + ("region", request.region), + ("network_policy", request.network_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 add_association( + self, + request: Optional[ + Union[compute.AddAssociationRegionNetworkPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy: Optional[str] = None, + network_policy_association_resource: Optional[ + compute.NetworkPolicyAssociation + ] = 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"""Inserts an association for the specified network + 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_v1beta + + def sample_add_association(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.AddAssociationRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.add_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.AddAssociationRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.AddAssociation. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_association_resource (google.cloud.compute_v1beta.types.NetworkPolicyAssociation): + The body resource for this request + This corresponds to the ``network_policy_association_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, + region, + network_policy, + network_policy_association_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.AddAssociationRegionNetworkPolicyRequest): + request = compute.AddAssociationRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + if network_policy_association_resource is not None: + request.network_policy_association_resource = ( + network_policy_association_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_association] + + # 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), + ("region", request.region), + ("network_policy", request.network_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._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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 add_traffic_classification_rule_unary( + self, + request: Optional[ + Union[compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy: Optional[str] = None, + network_policy_traffic_classification_rule_resource: Optional[ + compute.NetworkPolicyTrafficClassificationRule + ] = 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"""Inserts a rule into a network 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_v1beta + + def sample_add_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.AddTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.add_traffic_classification_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.AddTrafficClassificationRuleRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.AddTrafficClassificationRule. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_traffic_classification_rule_resource (google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule): + The body resource for this request + This corresponds to the ``network_policy_traffic_classification_rule_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, + region, + network_policy, + network_policy_traffic_classification_rule_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.AddTrafficClassificationRuleRegionNetworkPolicyRequest + ): + request = compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + if network_policy_traffic_classification_rule_resource is not None: + request.network_policy_traffic_classification_rule_resource = ( + network_policy_traffic_classification_rule_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.add_traffic_classification_rule + ] + + # 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), + ("region", request.region), + ("network_policy", request.network_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 add_traffic_classification_rule( + self, + request: Optional[ + Union[compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy: Optional[str] = None, + network_policy_traffic_classification_rule_resource: Optional[ + compute.NetworkPolicyTrafficClassificationRule + ] = 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"""Inserts a rule into a network 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_v1beta + + def sample_add_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.AddTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.add_traffic_classification_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.AddTrafficClassificationRuleRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.AddTrafficClassificationRule. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_traffic_classification_rule_resource (google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule): + The body resource for this request + This corresponds to the ``network_policy_traffic_classification_rule_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, + region, + network_policy, + network_policy_traffic_classification_rule_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.AddTrafficClassificationRuleRegionNetworkPolicyRequest + ): + request = compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + if network_policy_traffic_classification_rule_resource is not None: + request.network_policy_traffic_classification_rule_resource = ( + network_policy_traffic_classification_rule_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.add_traffic_classification_rule + ] + + # 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), + ("region", request.region), + ("network_policy", request.network_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._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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 aggregated_list( + self, + request: Optional[ + Union[compute.AggregatedListRegionNetworkPoliciesRequest, 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 an aggregated list of network policies. 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_v1beta + + def sample_aggregated_list(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.AggregatedListRegionNetworkPoliciesRequest( + 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_v1beta.types.AggregatedListRegionNetworkPoliciesRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.AggregatedList. + 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_v1beta.services.region_network_policies.pagers.AggregatedListPager: + 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.AggregatedListRegionNetworkPoliciesRequest): + request = compute.AggregatedListRegionNetworkPoliciesRequest(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.DeleteRegionNetworkPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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.Operation: + r"""Deletes the specified 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_v1beta + + def sample_delete(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.DeleteRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to delete. + + This corresponds to the ``network_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.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, region, network_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.DeleteRegionNetworkPolicyRequest): + request = compute.DeleteRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + + # 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), + ("region", request.region), + ("network_policy", request.network_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.DeleteRegionNetworkPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes the specified 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_v1beta + + def sample_delete(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.DeleteRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to delete. + + This corresponds to the ``network_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.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, region, network_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.DeleteRegionNetworkPolicyRequest): + request = compute.DeleteRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + + # 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), + ("region", request.region), + ("network_policy", request.network_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._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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.GetRegionNetworkPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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.NetworkPolicy: + r"""Returns the specified network 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_v1beta + + def sample_get(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to return. + + This corresponds to the ``network_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_v1beta.types.NetworkPolicy: + Represents a Network Policy resource. + """ + # 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, region, network_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.GetRegionNetworkPolicyRequest): + request = compute.GetRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_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), + ("region", request.region), + ("network_policy", request.network_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 get_association( + self, + request: Optional[ + Union[compute.GetAssociationRegionNetworkPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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.NetworkPolicyAssociation: + r"""Gets an association with the specified name. + + .. 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_v1beta + + def sample_get_association(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetAssociationRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetAssociationRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.GetAssociation. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy to which + the queried association belongs. + + This corresponds to the ``network_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_v1beta.types.NetworkPolicyAssociation: + + """ + # 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, region, network_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.GetAssociationRegionNetworkPolicyRequest): + request = compute.GetAssociationRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_association] + + # 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), + ("region", request.region), + ("network_policy", request.network_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 get_traffic_classification_rule( + self, + request: Optional[ + Union[compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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.NetworkPolicyTrafficClassificationRule: + r"""Gets a rule of the specified priority. + + .. 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_v1beta + + def sample_get_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get_traffic_classification_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetTrafficClassificationRuleRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.GetTrafficClassificationRule. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy to which + the queried rule belongs. + + This corresponds to the ``network_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_v1beta.types.NetworkPolicyTrafficClassificationRule: + Represents a traffic classification + rule that describes one or more match + conditions along with the action to be + taken when traffic matches this + condition. + + """ + # 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, region, network_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.GetTrafficClassificationRuleRegionNetworkPolicyRequest + ): + request = compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_traffic_classification_rule + ] + + # 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), + ("region", request.region), + ("network_policy", request.network_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.InsertRegionNetworkPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy_resource: Optional[compute.NetworkPolicy] = 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 policy in the specified project using + the data included in the request. + + .. 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_v1beta + + def sample_insert(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertRegionNetworkPolicyRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.InsertRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_resource (google.cloud.compute_v1beta.types.NetworkPolicy): + The body resource for this request + This corresponds to the ``network_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, region, network_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.InsertRegionNetworkPolicyRequest): + request = compute.InsertRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy_resource is not None: + request.network_policy_resource = network_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), + ("region", request.region), + ) + ), + ) + + # 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.InsertRegionNetworkPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy_resource: Optional[compute.NetworkPolicy] = 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 policy in the specified project using + the data included in the request. + + .. 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_v1beta + + def sample_insert(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertRegionNetworkPolicyRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.InsertRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_resource (google.cloud.compute_v1beta.types.NetworkPolicy): + The body resource for this request + This corresponds to the ``network_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, region, network_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.InsertRegionNetworkPolicyRequest): + request = compute.InsertRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy_resource is not None: + request.network_policy_resource = network_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), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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.ListRegionNetworkPoliciesRequest, dict]] = None, + *, + project: Optional[str] = None, + region: 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 all the policies that have been configured for + the specified project in the given region. + + .. 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_v1beta + + def sample_list(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.ListRegionNetworkPoliciesRequest( + project="project_value", + region="region_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_v1beta.types.ListRegionNetworkPoliciesRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` 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_v1beta.services.region_network_policies.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, region] + 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.ListRegionNetworkPoliciesRequest): + request = compute.ListRegionNetworkPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + + # 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), + ("region", request.region), + ) + ), + ) + + # 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 patch_unary( + self, + request: Optional[Union[compute.PatchRegionNetworkPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy: Optional[str] = None, + network_policy_resource: Optional[compute.NetworkPolicy] = 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"""Patches the specified policy with the data included + in the request. + + .. 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_v1beta + + def sample_patch(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PatchRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.Patch. 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_resource (google.cloud.compute_v1beta.types.NetworkPolicy): + The body resource for this request + This corresponds to the ``network_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, region, network_policy, network_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.PatchRegionNetworkPolicyRequest): + request = compute.PatchRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + if network_policy_resource is not None: + request.network_policy_resource = network_policy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # 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), + ("region", request.region), + ("network_policy", request.network_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 patch( + self, + request: Optional[Union[compute.PatchRegionNetworkPolicyRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy: Optional[str] = None, + network_policy_resource: Optional[compute.NetworkPolicy] = 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"""Patches the specified policy with the data included + in the request. + + .. 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_v1beta + + def sample_patch(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PatchRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.Patch. 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_resource (google.cloud.compute_v1beta.types.NetworkPolicy): + The body resource for this request + This corresponds to the ``network_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, region, network_policy, network_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.PatchRegionNetworkPolicyRequest): + request = compute.PatchRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + if network_policy_resource is not None: + request.network_policy_resource = network_policy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # 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), + ("region", request.region), + ("network_policy", request.network_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._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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 patch_traffic_classification_rule_unary( + self, + request: Optional[ + Union[ + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, dict + ] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy: Optional[str] = None, + network_policy_traffic_classification_rule_resource: Optional[ + compute.NetworkPolicyTrafficClassificationRule + ] = 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"""Patches a rule of the specified priority. + + .. 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_v1beta + + def sample_patch_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch_traffic_classification_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.PatchTrafficClassificationRule. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_traffic_classification_rule_resource (google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule): + The body resource for this request + This corresponds to the ``network_policy_traffic_classification_rule_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, + region, + network_policy, + network_policy_traffic_classification_rule_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.PatchTrafficClassificationRuleRegionNetworkPolicyRequest + ): + request = compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + if network_policy_traffic_classification_rule_resource is not None: + request.network_policy_traffic_classification_rule_resource = ( + network_policy_traffic_classification_rule_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.patch_traffic_classification_rule + ] + + # 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), + ("region", request.region), + ("network_policy", request.network_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 patch_traffic_classification_rule( + self, + request: Optional[ + Union[ + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, dict + ] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_policy: Optional[str] = None, + network_policy_traffic_classification_rule_resource: Optional[ + compute.NetworkPolicyTrafficClassificationRule + ] = 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"""Patches a rule of the specified priority. + + .. 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_v1beta + + def sample_patch_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch_traffic_classification_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.PatchTrafficClassificationRule. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy_traffic_classification_rule_resource (google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule): + The body resource for this request + This corresponds to the ``network_policy_traffic_classification_rule_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, + region, + network_policy, + network_policy_traffic_classification_rule_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.PatchTrafficClassificationRuleRegionNetworkPolicyRequest + ): + request = compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + if network_policy_traffic_classification_rule_resource is not None: + request.network_policy_traffic_classification_rule_resource = ( + network_policy_traffic_classification_rule_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.patch_traffic_classification_rule + ] + + # 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), + ("region", request.region), + ("network_policy", request.network_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._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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 remove_association_unary( + self, + request: Optional[ + Union[compute.RemoveAssociationRegionNetworkPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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.Operation: + r"""Removes an association for the specified network + 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_v1beta + + def sample_remove_association(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.RemoveAssociationRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.remove_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.RemoveAssociationRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.RemoveAssociation. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_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.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, region, network_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.RemoveAssociationRegionNetworkPolicyRequest): + request = compute.RemoveAssociationRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_association] + + # 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), + ("region", request.region), + ("network_policy", request.network_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 remove_association( + self, + request: Optional[ + Union[compute.RemoveAssociationRegionNetworkPolicyRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Removes an association for the specified network + 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_v1beta + + def sample_remove_association(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.RemoveAssociationRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.remove_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.RemoveAssociationRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.RemoveAssociation. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_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.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, region, network_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.RemoveAssociationRegionNetworkPolicyRequest): + request = compute.RemoveAssociationRegionNetworkPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_association] + + # 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), + ("region", request.region), + ("network_policy", request.network_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._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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 remove_traffic_classification_rule_unary( + self, + request: Optional[ + Union[ + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, dict + ] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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.Operation: + r"""Deletes a rule of the specified priority. + + .. 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_v1beta + + def sample_remove_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.remove_traffic_classification_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.RemoveTrafficClassificationRule. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_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.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, region, network_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.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest + ): + request = compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.remove_traffic_classification_rule + ] + + # 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), + ("region", request.region), + ("network_policy", request.network_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 remove_traffic_classification_rule( + self, + request: Optional[ + Union[ + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, dict + ] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + network_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]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes a rule of the specified priority. + + .. 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_v1beta + + def sample_remove_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.remove_traffic_classification_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, dict]): + The request object. A request message for + RegionNetworkPolicies.RemoveTrafficClassificationRule. + 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. + region (str): + Name of the region of this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + network_policy (str): + Name of the network policy resource + to update. + + This corresponds to the ``network_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.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, region, network_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.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest + ): + request = compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if network_policy is not None: + request.network_policy = network_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.remove_traffic_classification_rule + ] + + # 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), + ("region", request.region), + ("network_policy", request.network_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._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + 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) -> "RegionNetworkPoliciesClient": + 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__ = ("RegionNetworkPoliciesClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/pagers.py new file mode 100644 index 000000000000..97689cf06f1a --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/pagers.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_v1beta.types import compute + + +class AggregatedListPager: + """A pager for iterating through ``aggregated_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1beta.types.NetworkPolicyAggregatedList` 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_v1beta.types.NetworkPolicyAggregatedList` + 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.NetworkPolicyAggregatedList], + request: compute.AggregatedListRegionNetworkPoliciesRequest, + response: compute.NetworkPolicyAggregatedList, + *, + 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_v1beta.types.AggregatedListRegionNetworkPoliciesRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.NetworkPolicyAggregatedList): + 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.AggregatedListRegionNetworkPoliciesRequest(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.NetworkPolicyAggregatedList]: + 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.NetworkPoliciesScopedList]]: + for page in self.pages: + yield from page.items.items() + + def get(self, key: str) -> Optional[compute.NetworkPoliciesScopedList]: + 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_v1beta.types.NetworkPolicyList` 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_v1beta.types.NetworkPolicyList` + 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.NetworkPolicyList], + request: compute.ListRegionNetworkPoliciesRequest, + response: compute.NetworkPolicyList, + *, + 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_v1beta.types.ListRegionNetworkPoliciesRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.NetworkPolicyList): + 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.ListRegionNetworkPoliciesRequest(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.NetworkPolicyList]: + 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.NetworkPolicy]: + 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-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/README.rst new file mode 100644 index 000000000000..6caf6fb7e221 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RegionNetworkPoliciesTransport` is the ABC for all transports. +- public child `RegionNetworkPoliciesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RegionNetworkPoliciesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRegionNetworkPoliciesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RegionNetworkPoliciesRestTransport` 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-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/__init__.py new file mode 100644 index 000000000000..3aea4021a71d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 RegionNetworkPoliciesTransport +from .rest import ( + RegionNetworkPoliciesRestInterceptor, + RegionNetworkPoliciesRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[RegionNetworkPoliciesTransport]] +_transport_registry["rest"] = RegionNetworkPoliciesRestTransport + +__all__ = ( + "RegionNetworkPoliciesTransport", + "RegionNetworkPoliciesRestTransport", + "RegionNetworkPoliciesRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/base.py new file mode 100644 index 000000000000..abfc61f2aed9 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/base.py @@ -0,0 +1,360 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.compute_v1beta import gapic_version as package_version +from google.cloud.compute_v1beta.services import region_operations +from google.cloud.compute_v1beta.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 RegionNetworkPoliciesTransport(abc.ABC): + """Abstract transport class for RegionNetworkPolicies.""" + + 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. + """ + self._extended_operations_services: Dict[str, Any] = {} + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # 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_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # 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 + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.add_association: gapic_v1.method.wrap_method( + self.add_association, + default_timeout=None, + client_info=client_info, + ), + self.add_traffic_classification_rule: gapic_v1.method.wrap_method( + self.add_traffic_classification_rule, + default_timeout=None, + client_info=client_info, + ), + self.aggregated_list: gapic_v1.method.wrap_method( + self.aggregated_list, + default_timeout=None, + client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=None, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_timeout=None, + client_info=client_info, + ), + self.get_association: gapic_v1.method.wrap_method( + self.get_association, + default_timeout=None, + client_info=client_info, + ), + self.get_traffic_classification_rule: gapic_v1.method.wrap_method( + self.get_traffic_classification_rule, + default_timeout=None, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=None, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_timeout=None, + client_info=client_info, + ), + self.patch: gapic_v1.method.wrap_method( + self.patch, + default_timeout=None, + client_info=client_info, + ), + self.patch_traffic_classification_rule: gapic_v1.method.wrap_method( + self.patch_traffic_classification_rule, + default_timeout=None, + client_info=client_info, + ), + self.remove_association: gapic_v1.method.wrap_method( + self.remove_association, + default_timeout=None, + client_info=client_info, + ), + self.remove_traffic_classification_rule: gapic_v1.method.wrap_method( + self.remove_traffic_classification_rule, + default_timeout=None, + 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 add_association( + self, + ) -> Callable[ + [compute.AddAssociationRegionNetworkPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def add_traffic_classification_rule( + self, + ) -> Callable[ + [compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListRegionNetworkPoliciesRequest], + Union[ + compute.NetworkPolicyAggregatedList, + Awaitable[compute.NetworkPolicyAggregatedList], + ], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteRegionNetworkPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetRegionNetworkPolicyRequest], + Union[compute.NetworkPolicy, Awaitable[compute.NetworkPolicy]], + ]: + raise NotImplementedError() + + @property + def get_association( + self, + ) -> Callable[ + [compute.GetAssociationRegionNetworkPolicyRequest], + Union[ + compute.NetworkPolicyAssociation, + Awaitable[compute.NetworkPolicyAssociation], + ], + ]: + raise NotImplementedError() + + @property + def get_traffic_classification_rule( + self, + ) -> Callable[ + [compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest], + Union[ + compute.NetworkPolicyTrafficClassificationRule, + Awaitable[compute.NetworkPolicyTrafficClassificationRule], + ], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertRegionNetworkPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListRegionNetworkPoliciesRequest], + Union[compute.NetworkPolicyList, Awaitable[compute.NetworkPolicyList]], + ]: + raise NotImplementedError() + + @property + def patch( + self, + ) -> Callable[ + [compute.PatchRegionNetworkPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def patch_traffic_classification_rule( + self, + ) -> Callable[ + [compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def remove_association( + self, + ) -> Callable[ + [compute.RemoveAssociationRegionNetworkPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def remove_traffic_classification_rule( + self, + ) -> Callable[ + [compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _region_operations_client(self) -> region_operations.RegionOperationsClient: + ex_op_service = self._extended_operations_services.get("region_operations") + if not ex_op_service: + ex_op_service = region_operations.RegionOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["region_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("RegionNetworkPoliciesTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/rest.py new file mode 100644 index 000000000000..5d24432bbb11 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/rest.py @@ -0,0 +1,3166 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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 +import google.protobuf +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1beta.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseRegionNetworkPoliciesRestTransport + +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 RegionNetworkPoliciesRestInterceptor: + """Interceptor for RegionNetworkPolicies. + + 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 RegionNetworkPoliciesRestTransport. + + .. code-block:: python + class MyCustomRegionNetworkPoliciesInterceptor(RegionNetworkPoliciesRestInterceptor): + def pre_add_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_add_traffic_classification_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_traffic_classification_rule(self, response): + logging.log(f"Received response: {response}") + return response + + 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_get_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_traffic_classification_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_traffic_classification_rule(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_patch(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_patch(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_patch_traffic_classification_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_patch_traffic_classification_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_traffic_classification_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_traffic_classification_rule(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegionNetworkPoliciesRestTransport(interceptor=MyCustomRegionNetworkPoliciesInterceptor()) + client = RegionNetworkPoliciesClient(transport=transport) + + + """ + + def pre_add_association( + self, + request: compute.AddAssociationRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.AddAssociationRegionNetworkPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for add_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionNetworkPolicies server. + """ + return request, metadata + + def post_add_association(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for add_association + + DEPRECATED. Please use the `post_add_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionNetworkPolicies server but before + it is returned to user code. This `post_add_association` interceptor runs + before the `post_add_association_with_metadata` interceptor. + """ + return response + + def post_add_association_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 add_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionNetworkPolicies server but before it is returned to user code. + + We recommend only using this `post_add_association_with_metadata` + interceptor in new development instead of the `post_add_association` interceptor. + When both interceptors are used, this `post_add_association_with_metadata` interceptor runs after the + `post_add_association` interceptor. The (possibly modified) response returned by + `post_add_association` will be passed to + `post_add_association_with_metadata`. + """ + return response, metadata + + def pre_add_traffic_classification_rule( + self, + request: compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for add_traffic_classification_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionNetworkPolicies server. + """ + return request, metadata + + def post_add_traffic_classification_rule( + self, response: compute.Operation + ) -> compute.Operation: + """Post-rpc interceptor for add_traffic_classification_rule + + DEPRECATED. Please use the `post_add_traffic_classification_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionNetworkPolicies server but before + it is returned to user code. This `post_add_traffic_classification_rule` interceptor runs + before the `post_add_traffic_classification_rule_with_metadata` interceptor. + """ + return response + + def post_add_traffic_classification_rule_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 add_traffic_classification_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionNetworkPolicies server but before it is returned to user code. + + We recommend only using this `post_add_traffic_classification_rule_with_metadata` + interceptor in new development instead of the `post_add_traffic_classification_rule` interceptor. + When both interceptors are used, this `post_add_traffic_classification_rule_with_metadata` interceptor runs after the + `post_add_traffic_classification_rule` interceptor. The (possibly modified) response returned by + `post_add_traffic_classification_rule` will be passed to + `post_add_traffic_classification_rule_with_metadata`. + """ + return response, metadata + + def pre_aggregated_list( + self, + request: compute.AggregatedListRegionNetworkPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.AggregatedListRegionNetworkPoliciesRequest, + 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 RegionNetworkPolicies server. + """ + return request, metadata + + def post_aggregated_list( + self, response: compute.NetworkPolicyAggregatedList + ) -> compute.NetworkPolicyAggregatedList: + """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 RegionNetworkPolicies 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.NetworkPolicyAggregatedList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.NetworkPolicyAggregatedList, 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 RegionNetworkPolicies 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.DeleteRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.DeleteRegionNetworkPolicyRequest, + 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 RegionNetworkPolicies 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 RegionNetworkPolicies 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 RegionNetworkPolicies 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.GetRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetRegionNetworkPolicyRequest, 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 RegionNetworkPolicies server. + """ + return request, metadata + + def post_get(self, response: compute.NetworkPolicy) -> compute.NetworkPolicy: + """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 RegionNetworkPolicies 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.NetworkPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.NetworkPolicy, 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 RegionNetworkPolicies 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_get_association( + self, + request: compute.GetAssociationRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetAssociationRegionNetworkPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionNetworkPolicies server. + """ + return request, metadata + + def post_get_association( + self, response: compute.NetworkPolicyAssociation + ) -> compute.NetworkPolicyAssociation: + """Post-rpc interceptor for get_association + + DEPRECATED. Please use the `post_get_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionNetworkPolicies server but before + it is returned to user code. This `post_get_association` interceptor runs + before the `post_get_association_with_metadata` interceptor. + """ + return response + + def post_get_association_with_metadata( + self, + response: compute.NetworkPolicyAssociation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.NetworkPolicyAssociation, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionNetworkPolicies server but before it is returned to user code. + + We recommend only using this `post_get_association_with_metadata` + interceptor in new development instead of the `post_get_association` interceptor. + When both interceptors are used, this `post_get_association_with_metadata` interceptor runs after the + `post_get_association` interceptor. The (possibly modified) response returned by + `post_get_association` will be passed to + `post_get_association_with_metadata`. + """ + return response, metadata + + def pre_get_traffic_classification_rule( + self, + request: compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_traffic_classification_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionNetworkPolicies server. + """ + return request, metadata + + def post_get_traffic_classification_rule( + self, response: compute.NetworkPolicyTrafficClassificationRule + ) -> compute.NetworkPolicyTrafficClassificationRule: + """Post-rpc interceptor for get_traffic_classification_rule + + DEPRECATED. Please use the `post_get_traffic_classification_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionNetworkPolicies server but before + it is returned to user code. This `post_get_traffic_classification_rule` interceptor runs + before the `post_get_traffic_classification_rule_with_metadata` interceptor. + """ + return response + + def post_get_traffic_classification_rule_with_metadata( + self, + response: compute.NetworkPolicyTrafficClassificationRule, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.NetworkPolicyTrafficClassificationRule, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_traffic_classification_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionNetworkPolicies server but before it is returned to user code. + + We recommend only using this `post_get_traffic_classification_rule_with_metadata` + interceptor in new development instead of the `post_get_traffic_classification_rule` interceptor. + When both interceptors are used, this `post_get_traffic_classification_rule_with_metadata` interceptor runs after the + `post_get_traffic_classification_rule` interceptor. The (possibly modified) response returned by + `post_get_traffic_classification_rule` will be passed to + `post_get_traffic_classification_rule_with_metadata`. + """ + return response, metadata + + def pre_insert( + self, + request: compute.InsertRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.InsertRegionNetworkPolicyRequest, + 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 RegionNetworkPolicies 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 RegionNetworkPolicies 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 RegionNetworkPolicies 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.ListRegionNetworkPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListRegionNetworkPoliciesRequest, + 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 RegionNetworkPolicies server. + """ + return request, metadata + + def post_list( + self, response: compute.NetworkPolicyList + ) -> compute.NetworkPolicyList: + """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 RegionNetworkPolicies 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.NetworkPolicyList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.NetworkPolicyList, 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 RegionNetworkPolicies 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_patch( + self, + request: compute.PatchRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.PatchRegionNetworkPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for patch + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionNetworkPolicies server. + """ + return request, metadata + + def post_patch(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for patch + + DEPRECATED. Please use the `post_patch_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionNetworkPolicies server but before + it is returned to user code. This `post_patch` interceptor runs + before the `post_patch_with_metadata` interceptor. + """ + return response + + def post_patch_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 patch + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionNetworkPolicies server but before it is returned to user code. + + We recommend only using this `post_patch_with_metadata` + interceptor in new development instead of the `post_patch` interceptor. + When both interceptors are used, this `post_patch_with_metadata` interceptor runs after the + `post_patch` interceptor. The (possibly modified) response returned by + `post_patch` will be passed to + `post_patch_with_metadata`. + """ + return response, metadata + + def pre_patch_traffic_classification_rule( + self, + request: compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for patch_traffic_classification_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionNetworkPolicies server. + """ + return request, metadata + + def post_patch_traffic_classification_rule( + self, response: compute.Operation + ) -> compute.Operation: + """Post-rpc interceptor for patch_traffic_classification_rule + + DEPRECATED. Please use the `post_patch_traffic_classification_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionNetworkPolicies server but before + it is returned to user code. This `post_patch_traffic_classification_rule` interceptor runs + before the `post_patch_traffic_classification_rule_with_metadata` interceptor. + """ + return response + + def post_patch_traffic_classification_rule_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 patch_traffic_classification_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionNetworkPolicies server but before it is returned to user code. + + We recommend only using this `post_patch_traffic_classification_rule_with_metadata` + interceptor in new development instead of the `post_patch_traffic_classification_rule` interceptor. + When both interceptors are used, this `post_patch_traffic_classification_rule_with_metadata` interceptor runs after the + `post_patch_traffic_classification_rule` interceptor. The (possibly modified) response returned by + `post_patch_traffic_classification_rule` will be passed to + `post_patch_traffic_classification_rule_with_metadata`. + """ + return response, metadata + + def pre_remove_association( + self, + request: compute.RemoveAssociationRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.RemoveAssociationRegionNetworkPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for remove_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionNetworkPolicies server. + """ + return request, metadata + + def post_remove_association(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for remove_association + + DEPRECATED. Please use the `post_remove_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionNetworkPolicies server but before + it is returned to user code. This `post_remove_association` interceptor runs + before the `post_remove_association_with_metadata` interceptor. + """ + return response + + def post_remove_association_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 remove_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionNetworkPolicies server but before it is returned to user code. + + We recommend only using this `post_remove_association_with_metadata` + interceptor in new development instead of the `post_remove_association` interceptor. + When both interceptors are used, this `post_remove_association_with_metadata` interceptor runs after the + `post_remove_association` interceptor. The (possibly modified) response returned by + `post_remove_association` will be passed to + `post_remove_association_with_metadata`. + """ + return response, metadata + + def pre_remove_traffic_classification_rule( + self, + request: compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for remove_traffic_classification_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionNetworkPolicies server. + """ + return request, metadata + + def post_remove_traffic_classification_rule( + self, response: compute.Operation + ) -> compute.Operation: + """Post-rpc interceptor for remove_traffic_classification_rule + + DEPRECATED. Please use the `post_remove_traffic_classification_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionNetworkPolicies server but before + it is returned to user code. This `post_remove_traffic_classification_rule` interceptor runs + before the `post_remove_traffic_classification_rule_with_metadata` interceptor. + """ + return response + + def post_remove_traffic_classification_rule_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 remove_traffic_classification_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionNetworkPolicies server but before it is returned to user code. + + We recommend only using this `post_remove_traffic_classification_rule_with_metadata` + interceptor in new development instead of the `post_remove_traffic_classification_rule` interceptor. + When both interceptors are used, this `post_remove_traffic_classification_rule_with_metadata` interceptor runs after the + `post_remove_traffic_classification_rule` interceptor. The (possibly modified) response returned by + `post_remove_traffic_classification_rule` will be passed to + `post_remove_traffic_classification_rule_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class RegionNetworkPoliciesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionNetworkPoliciesRestInterceptor + + +class RegionNetworkPoliciesRestTransport(_BaseRegionNetworkPoliciesRestTransport): + """REST backend synchronous transport for RegionNetworkPolicies. + + The RegionNetworkPolicies 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[RegionNetworkPoliciesRestInterceptor] = 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. + """ + # 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 RegionNetworkPoliciesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AddAssociation( + _BaseRegionNetworkPoliciesRestTransport._BaseAddAssociation, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.AddAssociation") + + @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.AddAssociationRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the add association method over HTTP. + + Args: + request (~.compute.AddAssociationRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.AddAssociation. + 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, read Handling 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 = ( + _BaseRegionNetworkPoliciesRestTransport._BaseAddAssociation._get_http_options() + ) + + request, metadata = self._interceptor.pre_add_association(request, metadata) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseAddAssociation._get_transcoded_request( + http_options, request + ) + + body = _BaseRegionNetworkPoliciesRestTransport._BaseAddAssociation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._BaseAddAssociation._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_v1beta.RegionNetworkPoliciesClient.AddAssociation", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "AddAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._AddAssociation._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_add_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_add_association_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_v1beta.RegionNetworkPoliciesClient.add_association", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "AddAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _AddTrafficClassificationRule( + _BaseRegionNetworkPoliciesRestTransport._BaseAddTrafficClassificationRule, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash( + "RegionNetworkPoliciesRestTransport.AddTrafficClassificationRule" + ) + + @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.AddTrafficClassificationRuleRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the add traffic + classification rule method over HTTP. + + Args: + request (~.compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.AddTrafficClassificationRule. + 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, read Handling 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 = ( + _BaseRegionNetworkPoliciesRestTransport._BaseAddTrafficClassificationRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_add_traffic_classification_rule( + request, metadata + ) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseAddTrafficClassificationRule._get_transcoded_request( + http_options, request + ) + + body = _BaseRegionNetworkPoliciesRestTransport._BaseAddTrafficClassificationRule._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._BaseAddTrafficClassificationRule._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_v1beta.RegionNetworkPoliciesClient.AddTrafficClassificationRule", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "AddTrafficClassificationRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._AddTrafficClassificationRule._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_add_traffic_classification_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_add_traffic_classification_rule_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_v1beta.RegionNetworkPoliciesClient.add_traffic_classification_rule", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "AddTrafficClassificationRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _AggregatedList( + _BaseRegionNetworkPoliciesRestTransport._BaseAggregatedList, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.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.AggregatedListRegionNetworkPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.NetworkPolicyAggregatedList: + r"""Call the aggregated list method over HTTP. + + Args: + request (~.compute.AggregatedListRegionNetworkPoliciesRequest): + The request object. A request message for + RegionNetworkPolicies.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.NetworkPolicyAggregatedList: + + """ + + http_options = ( + _BaseRegionNetworkPoliciesRestTransport._BaseAggregatedList._get_http_options() + ) + + request, metadata = self._interceptor.pre_aggregated_list(request, metadata) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseAggregatedList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._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_v1beta.RegionNetworkPoliciesClient.AggregatedList", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "AggregatedList", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._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.NetworkPolicyAggregatedList() + pb_resp = compute.NetworkPolicyAggregatedList.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.NetworkPolicyAggregatedList.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_v1beta.RegionNetworkPoliciesClient.aggregated_list", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "AggregatedList", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Delete( + _BaseRegionNetworkPoliciesRestTransport._BaseDelete, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.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.DeleteRegionNetworkPolicyRequest, + *, + 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.DeleteRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.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, read Handling 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 = ( + _BaseRegionNetworkPoliciesRestTransport._BaseDelete._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete(request, metadata) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseDelete._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._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_v1beta.RegionNetworkPoliciesClient.Delete", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "Delete", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._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_v1beta.RegionNetworkPoliciesClient.delete", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "Delete", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Get( + _BaseRegionNetworkPoliciesRestTransport._BaseGet, RegionNetworkPoliciesRestStub + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.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.GetRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.NetworkPolicy: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.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.NetworkPolicy: + Represents a Network Policy resource. + """ + + http_options = ( + _BaseRegionNetworkPoliciesRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseRegionNetworkPoliciesRestTransport._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_v1beta.RegionNetworkPoliciesClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._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.NetworkPolicy() + pb_resp = compute.NetworkPolicy.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.NetworkPolicy.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_v1beta.RegionNetworkPoliciesClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAssociation( + _BaseRegionNetworkPoliciesRestTransport._BaseGetAssociation, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.GetAssociation") + + @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.GetAssociationRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.NetworkPolicyAssociation: + r"""Call the get association method over HTTP. + + Args: + request (~.compute.GetAssociationRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.GetAssociation. + 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.NetworkPolicyAssociation: + + """ + + http_options = ( + _BaseRegionNetworkPoliciesRestTransport._BaseGetAssociation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_association(request, metadata) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseGetAssociation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._BaseGetAssociation._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_v1beta.RegionNetworkPoliciesClient.GetAssociation", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "GetAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._GetAssociation._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.NetworkPolicyAssociation() + pb_resp = compute.NetworkPolicyAssociation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_association_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.NetworkPolicyAssociation.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_v1beta.RegionNetworkPoliciesClient.get_association", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "GetAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetTrafficClassificationRule( + _BaseRegionNetworkPoliciesRestTransport._BaseGetTrafficClassificationRule, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash( + "RegionNetworkPoliciesRestTransport.GetTrafficClassificationRule" + ) + + @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.GetTrafficClassificationRuleRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.NetworkPolicyTrafficClassificationRule: + r"""Call the get traffic + classification rule method over HTTP. + + Args: + request (~.compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.GetTrafficClassificationRule. + 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.NetworkPolicyTrafficClassificationRule: + Represents a traffic classification + rule that describes one or more match + conditions along with the action to be + taken when traffic matches this + condition. + + """ + + http_options = ( + _BaseRegionNetworkPoliciesRestTransport._BaseGetTrafficClassificationRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_traffic_classification_rule( + request, metadata + ) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseGetTrafficClassificationRule._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._BaseGetTrafficClassificationRule._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_v1beta.RegionNetworkPoliciesClient.GetTrafficClassificationRule", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "GetTrafficClassificationRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._GetTrafficClassificationRule._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.NetworkPolicyTrafficClassificationRule() + pb_resp = compute.NetworkPolicyTrafficClassificationRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_traffic_classification_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_get_traffic_classification_rule_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + compute.NetworkPolicyTrafficClassificationRule.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_v1beta.RegionNetworkPoliciesClient.get_traffic_classification_rule", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "GetTrafficClassificationRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Insert( + _BaseRegionNetworkPoliciesRestTransport._BaseInsert, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.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.InsertRegionNetworkPolicyRequest, + *, + 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.InsertRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.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, read Handling 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 = ( + _BaseRegionNetworkPoliciesRestTransport._BaseInsert._get_http_options() + ) + + request, metadata = self._interceptor.pre_insert(request, metadata) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseInsert._get_transcoded_request( + http_options, request + ) + + body = _BaseRegionNetworkPoliciesRestTransport._BaseInsert._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._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_v1beta.RegionNetworkPoliciesClient.Insert", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "Insert", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._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_v1beta.RegionNetworkPoliciesClient.insert", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "Insert", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List( + _BaseRegionNetworkPoliciesRestTransport._BaseList, RegionNetworkPoliciesRestStub + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.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.ListRegionNetworkPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.NetworkPolicyList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListRegionNetworkPoliciesRequest): + The request object. A request message for + RegionNetworkPolicies.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.NetworkPolicyList: + + """ + + http_options = ( + _BaseRegionNetworkPoliciesRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._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_v1beta.RegionNetworkPoliciesClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._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.NetworkPolicyList() + pb_resp = compute.NetworkPolicyList.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.NetworkPolicyList.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_v1beta.RegionNetworkPoliciesClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Patch( + _BaseRegionNetworkPoliciesRestTransport._BasePatch, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.Patch") + + @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.PatchRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the patch method over HTTP. + + Args: + request (~.compute.PatchRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.Patch. 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, read Handling 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 = ( + _BaseRegionNetworkPoliciesRestTransport._BasePatch._get_http_options() + ) + + request, metadata = self._interceptor.pre_patch(request, metadata) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BasePatch._get_transcoded_request( + http_options, request + ) + + body = _BaseRegionNetworkPoliciesRestTransport._BasePatch._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._BasePatch._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_v1beta.RegionNetworkPoliciesClient.Patch", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "Patch", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._Patch._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_patch(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_patch_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_v1beta.RegionNetworkPoliciesClient.patch", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "Patch", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PatchTrafficClassificationRule( + _BaseRegionNetworkPoliciesRestTransport._BasePatchTrafficClassificationRule, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash( + "RegionNetworkPoliciesRestTransport.PatchTrafficClassificationRule" + ) + + @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.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the patch traffic + classification rule method over HTTP. + + Args: + request (~.compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.PatchTrafficClassificationRule. + 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, read Handling 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 = ( + _BaseRegionNetworkPoliciesRestTransport._BasePatchTrafficClassificationRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_patch_traffic_classification_rule( + request, metadata + ) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BasePatchTrafficClassificationRule._get_transcoded_request( + http_options, request + ) + + body = _BaseRegionNetworkPoliciesRestTransport._BasePatchTrafficClassificationRule._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._BasePatchTrafficClassificationRule._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_v1beta.RegionNetworkPoliciesClient.PatchTrafficClassificationRule", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "PatchTrafficClassificationRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._PatchTrafficClassificationRule._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_patch_traffic_classification_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_patch_traffic_classification_rule_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_v1beta.RegionNetworkPoliciesClient.patch_traffic_classification_rule", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "PatchTrafficClassificationRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RemoveAssociation( + _BaseRegionNetworkPoliciesRestTransport._BaseRemoveAssociation, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash("RegionNetworkPoliciesRestTransport.RemoveAssociation") + + @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.RemoveAssociationRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the remove association method over HTTP. + + Args: + request (~.compute.RemoveAssociationRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.RemoveAssociation. + 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, read Handling 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 = ( + _BaseRegionNetworkPoliciesRestTransport._BaseRemoveAssociation._get_http_options() + ) + + request, metadata = self._interceptor.pre_remove_association( + request, metadata + ) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseRemoveAssociation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._BaseRemoveAssociation._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_v1beta.RegionNetworkPoliciesClient.RemoveAssociation", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "RemoveAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + RegionNetworkPoliciesRestTransport._RemoveAssociation._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_remove_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_remove_association_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_v1beta.RegionNetworkPoliciesClient.remove_association", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "RemoveAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RemoveTrafficClassificationRule( + _BaseRegionNetworkPoliciesRestTransport._BaseRemoveTrafficClassificationRule, + RegionNetworkPoliciesRestStub, + ): + def __hash__(self): + return hash( + "RegionNetworkPoliciesRestTransport.RemoveTrafficClassificationRule" + ) + + @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.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the remove traffic + classification rule method over HTTP. + + Args: + request (~.compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest): + The request object. A request message for + RegionNetworkPolicies.RemoveTrafficClassificationRule. + 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, read Handling 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 = ( + _BaseRegionNetworkPoliciesRestTransport._BaseRemoveTrafficClassificationRule._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_remove_traffic_classification_rule( + request, metadata + ) + transcoded_request = _BaseRegionNetworkPoliciesRestTransport._BaseRemoveTrafficClassificationRule._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionNetworkPoliciesRestTransport._BaseRemoveTrafficClassificationRule._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_v1beta.RegionNetworkPoliciesClient.RemoveTrafficClassificationRule", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "RemoveTrafficClassificationRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionNetworkPoliciesRestTransport._RemoveTrafficClassificationRule._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_remove_traffic_classification_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_remove_traffic_classification_rule_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_v1beta.RegionNetworkPoliciesClient.remove_traffic_classification_rule", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "rpcName": "RemoveTrafficClassificationRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def add_association( + self, + ) -> Callable[ + [compute.AddAssociationRegionNetworkPolicyRequest], 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._AddAssociation(self._session, self._host, self._interceptor) # type: ignore + + @property + def add_traffic_classification_rule( + self, + ) -> Callable[ + [compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest], + 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._AddTrafficClassificationRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListRegionNetworkPoliciesRequest], + compute.NetworkPolicyAggregatedList, + ]: + # 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.DeleteRegionNetworkPolicyRequest], 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.GetRegionNetworkPolicyRequest], compute.NetworkPolicy]: + # 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 get_association( + self, + ) -> Callable[ + [compute.GetAssociationRegionNetworkPolicyRequest], + compute.NetworkPolicyAssociation, + ]: + # 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._GetAssociation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_traffic_classification_rule( + self, + ) -> Callable[ + [compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest], + compute.NetworkPolicyTrafficClassificationRule, + ]: + # 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._GetTrafficClassificationRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert( + self, + ) -> Callable[[compute.InsertRegionNetworkPolicyRequest], 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.ListRegionNetworkPoliciesRequest], compute.NetworkPolicyList + ]: + # 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 patch( + self, + ) -> Callable[[compute.PatchRegionNetworkPolicyRequest], 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._Patch(self._session, self._host, self._interceptor) # type: ignore + + @property + def patch_traffic_classification_rule( + self, + ) -> Callable[ + [compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest], + 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._PatchTrafficClassificationRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_association( + self, + ) -> Callable[ + [compute.RemoveAssociationRegionNetworkPolicyRequest], 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._RemoveAssociation(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_traffic_classification_rule( + self, + ) -> Callable[ + [compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest], + 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._RemoveTrafficClassificationRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("RegionNetworkPoliciesRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/rest_base.py new file mode 100644 index 000000000000..d16e4086a35c --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_network_policies/transports/rest_base.py @@ -0,0 +1,755 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_v1beta.types import compute + +from .base import DEFAULT_CLIENT_INFO, RegionNetworkPoliciesTransport + + +class _BaseRegionNetworkPoliciesRestTransport(RegionNetworkPoliciesTransport): + """Base REST backend transport for RegionNetworkPolicies. + + 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 _BaseAddAssociation: + 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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/addAssociation", + "body": "network_policy_association_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AddAssociationRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BaseAddAssociation._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseAddTrafficClassificationRule: + 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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/addTrafficClassificationRule", + "body": "network_policy_traffic_classification_rule_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BaseAddTrafficClassificationRule._get_unset_required_fields( + query_params + ) + ) + + return query_params + + 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/beta/projects/{project}/aggregated/networkPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AggregatedListRegionNetworkPoliciesRequest.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( + _BaseRegionNetworkPoliciesRestTransport._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": "delete", + "uri": "/compute/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseGetAssociation: + 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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/getAssociation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetAssociationRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BaseGetAssociation._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseGetTrafficClassificationRule: + 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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/getTrafficClassificationRule", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BaseGetTrafficClassificationRule._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/beta/projects/{project}/regions/{region}/networkPolicies", + "body": "network_policy_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.InsertRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._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/beta/projects/{project}/regions/{region}/networkPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListRegionNetworkPoliciesRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BasePatch: + 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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}", + "body": "network_policy_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.PatchRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BasePatch._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BasePatchTrafficClassificationRule: + 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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/patchTrafficClassificationRule", + "body": "network_policy_traffic_classification_rule_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BasePatchTrafficClassificationRule._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseRemoveAssociation: + 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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/removeAssociation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.RemoveAssociationRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BaseRemoveAssociation._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseRemoveTrafficClassificationRule: + 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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/removeTrafficClassificationRule", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest.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( + _BaseRegionNetworkPoliciesRestTransport._BaseRemoveTrafficClassificationRule._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseRegionNetworkPoliciesRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_snapshots/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_snapshots/client.py index c63c7d9e2d1e..c068f0f96eab 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_snapshots/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_snapshots/client.py @@ -1076,7 +1076,7 @@ def sample_get(): resource. You can use snapshots to back up data on a regular interval. For more information, read Creating persistent - disk snapshots. LINT.IfChange + disk snapshots. """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_snapshots/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_snapshots/transports/rest.py index 540c765d79b1..3a8e57c293ee 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_snapshots/transports/rest.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_snapshots/transports/rest.py @@ -831,7 +831,7 @@ def __call__( resource. You can use snapshots to back up data on a regular interval. For more information, read Creating persistent - disk snapshots. LINT.IfChange + disk snapshots. """ diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/client.py index 9486f23cf6f3..0047b8fa6bbc 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/client.py @@ -1328,6 +1328,369 @@ def error_code(self): # Done; return the response. return response + def report_faulty_unary( + self, + request: Optional[ + Union[compute.ReportFaultyReservationSubBlockRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + parent_name: Optional[str] = None, + reservation_sub_block: Optional[str] = None, + reservation_sub_blocks_report_faulty_request_resource: Optional[ + compute.ReservationSubBlocksReportFaultyRequest + ] = 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"""Allows customers to report a faulty subBlock. + + .. 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_v1beta + + def sample_report_faulty(): + # Create a client + client = compute_v1beta.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1beta.ReportFaultyReservationSubBlockRequest( + parent_name="parent_name_value", + project="project_value", + reservation_sub_block="reservation_sub_block_value", + zone="zone_value", + ) + + # Make the request + response = client.report_faulty(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ReportFaultyReservationSubBlockRequest, dict]): + The request object. A request message for + ReservationSubBlocks.ReportFaulty. 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. + zone (str): + Name of the zone for this request. + Zone name should conform to RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + parent_name (str): + The name of the parent reservation and parent block. In + the format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + + This corresponds to the ``parent_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_block (str): + The name of the reservation subBlock. + Name should conform to RFC1035 or be a + resource ID. + + This corresponds to the ``reservation_sub_block`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_blocks_report_faulty_request_resource (google.cloud.compute_v1beta.types.ReservationSubBlocksReportFaultyRequest): + The body resource for this request + This corresponds to the ``reservation_sub_blocks_report_faulty_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, + zone, + parent_name, + reservation_sub_block, + reservation_sub_blocks_report_faulty_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.ReportFaultyReservationSubBlockRequest): + request = compute.ReportFaultyReservationSubBlockRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if parent_name is not None: + request.parent_name = parent_name + if reservation_sub_block is not None: + request.reservation_sub_block = reservation_sub_block + if reservation_sub_blocks_report_faulty_request_resource is not None: + request.reservation_sub_blocks_report_faulty_request_resource = ( + reservation_sub_blocks_report_faulty_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report_faulty] + + # 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), + ("zone", request.zone), + ("parent_name", request.parent_name), + ("reservation_sub_block", request.reservation_sub_block), + ) + ), + ) + + # 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 report_faulty( + self, + request: Optional[ + Union[compute.ReportFaultyReservationSubBlockRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + parent_name: Optional[str] = None, + reservation_sub_block: Optional[str] = None, + reservation_sub_blocks_report_faulty_request_resource: Optional[ + compute.ReservationSubBlocksReportFaultyRequest + ] = 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"""Allows customers to report a faulty subBlock. + + .. 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_v1beta + + def sample_report_faulty(): + # Create a client + client = compute_v1beta.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1beta.ReportFaultyReservationSubBlockRequest( + parent_name="parent_name_value", + project="project_value", + reservation_sub_block="reservation_sub_block_value", + zone="zone_value", + ) + + # Make the request + response = client.report_faulty(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ReportFaultyReservationSubBlockRequest, dict]): + The request object. A request message for + ReservationSubBlocks.ReportFaulty. 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. + zone (str): + Name of the zone for this request. + Zone name should conform to RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + parent_name (str): + The name of the parent reservation and parent block. In + the format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + + This corresponds to the ``parent_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_block (str): + The name of the reservation subBlock. + Name should conform to RFC1035 or be a + resource ID. + + This corresponds to the ``reservation_sub_block`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_blocks_report_faulty_request_resource (google.cloud.compute_v1beta.types.ReservationSubBlocksReportFaultyRequest): + The body resource for this request + This corresponds to the ``reservation_sub_blocks_report_faulty_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, + zone, + parent_name, + reservation_sub_block, + reservation_sub_blocks_report_faulty_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.ReportFaultyReservationSubBlockRequest): + request = compute.ReportFaultyReservationSubBlockRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if parent_name is not None: + request.parent_name = parent_name + if reservation_sub_block is not None: + request.reservation_sub_block = reservation_sub_block + if reservation_sub_blocks_report_faulty_request_resource is not None: + request.reservation_sub_blocks_report_faulty_request_resource = ( + reservation_sub_blocks_report_faulty_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report_faulty] + + # 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), + ("zone", request.zone), + ("parent_name", request.parent_name), + ("reservation_sub_block", request.reservation_sub_block), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + 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) -> "ReservationSubBlocksClient": return self diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/base.py index f1dbdb482d27..54130a98e961 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/base.py @@ -153,6 +153,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.report_faulty: gapic_v1.method.wrap_method( + self.report_faulty, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -197,6 +202,15 @@ def perform_maintenance( ]: raise NotImplementedError() + @property + def report_faulty( + self, + ) -> Callable[ + [compute.ReportFaultyReservationSubBlockRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest.py index 292813a27978..02d99ef25e08 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest.py @@ -96,6 +96,14 @@ def post_perform_maintenance(self, response): logging.log(f"Received response: {response}") return response + def pre_report_faulty(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_report_faulty(self, response): + logging.log(f"Received response: {response}") + return response + transport = ReservationSubBlocksRestTransport(interceptor=MyCustomReservationSubBlocksInterceptor()) client = ReservationSubBlocksClient(transport=transport) @@ -252,6 +260,53 @@ def post_perform_maintenance_with_metadata( """ return response, metadata + def pre_report_faulty( + self, + request: compute.ReportFaultyReservationSubBlockRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ReportFaultyReservationSubBlockRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for report_faulty + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationSubBlocks server. + """ + return request, metadata + + def post_report_faulty(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for report_faulty + + DEPRECATED. Please use the `post_report_faulty_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ReservationSubBlocks server but before + it is returned to user code. This `post_report_faulty` interceptor runs + before the `post_report_faulty_with_metadata` interceptor. + """ + return response + + def post_report_faulty_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 report_faulty + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ReservationSubBlocks server but before it is returned to user code. + + We recommend only using this `post_report_faulty_with_metadata` + interceptor in new development instead of the `post_report_faulty` interceptor. + When both interceptors are used, this `post_report_faulty_with_metadata` interceptor runs after the + `post_report_faulty` interceptor. The (possibly modified) response returned by + `post_report_faulty` will be passed to + `post_report_faulty_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class ReservationSubBlocksRestStub: @@ -812,6 +867,176 @@ def __call__( ) return resp + class _ReportFaulty( + _BaseReservationSubBlocksRestTransport._BaseReportFaulty, + ReservationSubBlocksRestStub, + ): + def __hash__(self): + return hash("ReservationSubBlocksRestTransport.ReportFaulty") + + @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.ReportFaultyReservationSubBlockRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the report faulty method over HTTP. + + Args: + request (~.compute.ReportFaultyReservationSubBlockRequest): + The request object. A request message for + ReservationSubBlocks.ReportFaulty. 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, read Handling 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 = ( + _BaseReservationSubBlocksRestTransport._BaseReportFaulty._get_http_options() + ) + + request, metadata = self._interceptor.pre_report_faulty(request, metadata) + transcoded_request = _BaseReservationSubBlocksRestTransport._BaseReportFaulty._get_transcoded_request( + http_options, request + ) + + body = _BaseReservationSubBlocksRestTransport._BaseReportFaulty._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseReservationSubBlocksRestTransport._BaseReportFaulty._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_v1beta.ReservationSubBlocksClient.ReportFaulty", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "rpcName": "ReportFaulty", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ReservationSubBlocksRestTransport._ReportFaulty._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_report_faulty(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_report_faulty_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_v1beta.ReservationSubBlocksClient.report_faulty", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "rpcName": "ReportFaulty", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def get( self, @@ -843,6 +1068,14 @@ def perform_maintenance( # In C++ this would require a dynamic_cast return self._PerformMaintenance(self._session, self._host, self._interceptor) # type: ignore + @property + def report_faulty( + self, + ) -> Callable[[compute.ReportFaultyReservationSubBlockRequest], 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._ReportFaulty(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest_base.py index 310a6804f80a..3d24818c8d2b 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest_base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest_base.py @@ -227,5 +227,61 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseReportFaulty: + 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/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty", + "body": "reservation_sub_blocks_report_faulty_request_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ReportFaultyReservationSubBlockRequest.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( + _BaseReservationSubBlocksRestTransport._BaseReportFaulty._get_unset_required_fields( + query_params + ) + ) + + return query_params + __all__ = ("_BaseReservationSubBlocksRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/snapshots/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/snapshots/client.py index 5fad6a406a86..6c8346a50505 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/snapshots/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/snapshots/client.py @@ -1159,7 +1159,7 @@ def sample_get(): resource. You can use snapshots to back up data on a regular interval. For more information, read Creating persistent - disk snapshots. LINT.IfChange + disk snapshots. """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/snapshots/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/snapshots/transports/rest.py index 5b2e123096ea..93c333231345 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/snapshots/transports/rest.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/snapshots/transports/rest.py @@ -1022,7 +1022,7 @@ def __call__( resource. You can use snapshots to back up data on a regular interval. For more information, read Creating persistent - disk snapshots. LINT.IfChange + disk snapshots. """ diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py index 4eb9e75ae0af..c235aa673344 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py @@ -28,6 +28,7 @@ AddAssociationNetworkFirewallPolicyRequest, AddAssociationOrganizationSecurityPolicyRequest, AddAssociationRegionNetworkFirewallPolicyRequest, + AddAssociationRegionNetworkPolicyRequest, AddHealthCheckTargetPoolRequest, AddInstancesInstanceGroupRequest, AddInstanceTargetPoolRequest, @@ -51,6 +52,7 @@ AddRuleSecurityPolicyRequest, AddSignedUrlKeyBackendBucketRequest, AddSignedUrlKeyBackendServiceRequest, + AddTrafficClassificationRuleRegionNetworkPolicyRequest, AdvancedMachineFeatures, AggregatedListAcceleratorTypesRequest, AggregatedListAddressesRequest, @@ -79,6 +81,8 @@ AggregatedListPacketMirroringsRequest, AggregatedListPublicDelegatedPrefixesRequest, AggregatedListRegionCommitmentsRequest, + AggregatedListRegionHealthSourcesRequest, + AggregatedListRegionNetworkPoliciesRequest, AggregatedListReservationsRequest, AggregatedListResourcePoliciesRequest, AggregatedListRoutersRequest, @@ -290,6 +294,7 @@ DeleteRegionDiskRequest, DeleteRegionHealthCheckRequest, DeleteRegionHealthCheckServiceRequest, + DeleteRegionHealthSourceRequest, DeleteRegionInstanceGroupManagerRequest, DeleteRegionInstanceGroupManagerResizeRequestRequest, DeleteRegionInstanceTemplateRequest, @@ -297,6 +302,7 @@ DeleteRegionMultiMigRequest, DeleteRegionNetworkEndpointGroupRequest, DeleteRegionNetworkFirewallPolicyRequest, + DeleteRegionNetworkPolicyRequest, DeleteRegionNotificationEndpointRequest, DeleteRegionOperationRequest, DeleteRegionOperationResponse, @@ -434,6 +440,7 @@ GetAssociationNetworkFirewallPolicyRequest, GetAssociationOrganizationSecurityPolicyRequest, GetAssociationRegionNetworkFirewallPolicyRequest, + GetAssociationRegionNetworkPolicyRequest, GetAutoscalerRequest, GetBackendBucketRequest, GetBackendServiceRequest, @@ -540,6 +547,7 @@ GetRegionDiskTypeRequest, GetRegionHealthCheckRequest, GetRegionHealthCheckServiceRequest, + GetRegionHealthSourceRequest, GetRegionInstanceGroupManagerRequest, GetRegionInstanceGroupManagerResizeRequestRequest, GetRegionInstanceGroupRequest, @@ -548,6 +556,7 @@ GetRegionMultiMigRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, + GetRegionNetworkPolicyRequest, GetRegionNotificationEndpointRequest, GetRegionOperationRequest, GetRegionRequest, @@ -596,6 +605,7 @@ GetTargetSslProxyRequest, GetTargetTcpProxyRequest, GetTargetVpnGatewayRequest, + GetTrafficClassificationRuleRegionNetworkPolicyRequest, GetUrlMapRequest, GetVpnGatewayRequest, GetVpnTunnelRequest, @@ -626,6 +636,10 @@ HealthCheckServiceReference, HealthCheckServicesList, HealthChecksScopedList, + HealthSource, + HealthSourceAggregatedList, + HealthSourceList, + HealthSourcesScopedList, HealthStatus, HealthStatusForNetworkEndpoint, Help, @@ -650,6 +664,7 @@ Image, ImageFamilyView, ImageList, + ImageParams, InitialStateConfig, InsertAddressRequest, InsertAutoscalerRequest, @@ -697,6 +712,7 @@ InsertRegionDiskRequest, InsertRegionHealthCheckRequest, InsertRegionHealthCheckServiceRequest, + InsertRegionHealthSourceRequest, InsertRegionInstanceGroupManagerRequest, InsertRegionInstanceGroupManagerResizeRequestRequest, InsertRegionInstanceTemplateRequest, @@ -704,6 +720,7 @@ InsertRegionMultiMigRequest, InsertRegionNetworkEndpointGroupRequest, InsertRegionNetworkFirewallPolicyRequest, + InsertRegionNetworkPolicyRequest, InsertRegionNotificationEndpointRequest, InsertRegionSecurityPolicyRequest, InsertRegionSnapshotRequest, @@ -994,6 +1011,7 @@ ListRegionDiskTypesRequest, ListRegionHealthCheckServicesRequest, ListRegionHealthChecksRequest, + ListRegionHealthSourcesRequest, ListRegionInstanceGroupManagerResizeRequestsRequest, ListRegionInstanceGroupManagersRequest, ListRegionInstanceGroupsRequest, @@ -1002,6 +1020,7 @@ ListRegionMultiMigsRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, + ListRegionNetworkPoliciesRequest, ListRegionNotificationEndpointsRequest, ListRegionOperationsRequest, ListRegionSecurityPoliciesRequest, @@ -1121,6 +1140,16 @@ NetworkPeeringConnectionStatusConsensusState, NetworkPeeringConnectionStatusTrafficConfiguration, NetworkPerformanceConfig, + NetworkPoliciesScopedList, + NetworkPolicy, + NetworkPolicyAggregatedList, + NetworkPolicyAssociation, + NetworkPolicyList, + NetworkPolicyTrafficClassificationRule, + NetworkPolicyTrafficClassificationRuleAction, + NetworkPolicyTrafficClassificationRuleMatcher, + NetworkPolicyTrafficClassificationRuleMatcherLayer4Config, + NetworkPolicyTrafficClassificationRuleSecureTag, NetworkProfile, NetworkProfileLocation, NetworkProfileNetworkFeatures, @@ -1215,8 +1244,10 @@ PatchRegionDiskSettingRequest, PatchRegionHealthCheckRequest, PatchRegionHealthCheckServiceRequest, + PatchRegionHealthSourceRequest, PatchRegionInstanceGroupManagerRequest, PatchRegionNetworkFirewallPolicyRequest, + PatchRegionNetworkPolicyRequest, PatchRegionSecurityPolicyRequest, PatchRegionSnapshotSettingRequest, PatchRegionSslPolicyRequest, @@ -1239,6 +1270,7 @@ PatchTargetGrpcProxyRequest, PatchTargetHttpProxyRequest, PatchTargetHttpsProxyRequest, + PatchTrafficClassificationRuleRegionNetworkPolicyRequest, PatchUrlMapRequest, PatchWireGroupRequest, PathMatcher, @@ -1332,6 +1364,7 @@ RemoveAssociationNetworkFirewallPolicyRequest, RemoveAssociationOrganizationSecurityPolicyRequest, RemoveAssociationRegionNetworkFirewallPolicyRequest, + RemoveAssociationRegionNetworkPolicyRequest, RemoveHealthCheckTargetPoolRequest, RemoveInstancesInstanceGroupRequest, RemoveInstanceTargetPoolRequest, @@ -1347,6 +1380,8 @@ RemoveRuleRegionNetworkFirewallPolicyRequest, RemoveRuleRegionSecurityPolicyRequest, RemoveRuleSecurityPolicyRequest, + RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, + ReportFaultyReservationSubBlockRequest, ReportHostAsFaultyInstanceRequest, RequestMirrorPolicy, RequestRemovePeeringNetworkRequest, @@ -1371,6 +1406,8 @@ ReservationSubBlockPhysicalTopology, ReservationSubBlocksGetResponse, ReservationSubBlocksListResponse, + ReservationSubBlocksReportFaultyRequest, + ReservationSubBlocksReportFaultyRequestFaultReason, ResetInstanceRequest, ResizeAdvancedInstanceGroupManagerRequest, ResizeAdvancedRegionInstanceGroupManagerRequest, @@ -1617,6 +1654,7 @@ Snapshot, SnapshotAggregatedList, SnapshotList, + SnapshotParams, SnapshotSettings, SnapshotSettingsAccessLocation, SnapshotSettingsAccessLocationAccessLocationPreference, @@ -1771,6 +1809,7 @@ TestIamPermissionsRegionDiskRequest, TestIamPermissionsRegionHealthCheckRequest, TestIamPermissionsRegionHealthCheckServiceRequest, + TestIamPermissionsRegionHealthSourceRequest, TestIamPermissionsRegionInstanceGroupManagerRequest, TestIamPermissionsRegionInstanceGroupRequest, TestIamPermissionsRegionInstantSnapshotRequest, @@ -1922,6 +1961,7 @@ "AddAssociationNetworkFirewallPolicyRequest", "AddAssociationOrganizationSecurityPolicyRequest", "AddAssociationRegionNetworkFirewallPolicyRequest", + "AddAssociationRegionNetworkPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstancesInstanceGroupRequest", "AddInstanceTargetPoolRequest", @@ -1945,6 +1985,7 @@ "AddRuleSecurityPolicyRequest", "AddSignedUrlKeyBackendBucketRequest", "AddSignedUrlKeyBackendServiceRequest", + "AddTrafficClassificationRuleRegionNetworkPolicyRequest", "AdvancedMachineFeatures", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", @@ -1973,6 +2014,8 @@ "AggregatedListPacketMirroringsRequest", "AggregatedListPublicDelegatedPrefixesRequest", "AggregatedListRegionCommitmentsRequest", + "AggregatedListRegionHealthSourcesRequest", + "AggregatedListRegionNetworkPoliciesRequest", "AggregatedListReservationsRequest", "AggregatedListResourcePoliciesRequest", "AggregatedListRoutersRequest", @@ -2184,6 +2227,7 @@ "DeleteRegionDiskRequest", "DeleteRegionHealthCheckRequest", "DeleteRegionHealthCheckServiceRequest", + "DeleteRegionHealthSourceRequest", "DeleteRegionInstanceGroupManagerRequest", "DeleteRegionInstanceGroupManagerResizeRequestRequest", "DeleteRegionInstanceTemplateRequest", @@ -2191,6 +2235,7 @@ "DeleteRegionMultiMigRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", + "DeleteRegionNetworkPolicyRequest", "DeleteRegionNotificationEndpointRequest", "DeleteRegionOperationRequest", "DeleteRegionOperationResponse", @@ -2328,6 +2373,7 @@ "GetAssociationNetworkFirewallPolicyRequest", "GetAssociationOrganizationSecurityPolicyRequest", "GetAssociationRegionNetworkFirewallPolicyRequest", + "GetAssociationRegionNetworkPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", "GetBackendServiceRequest", @@ -2434,6 +2480,7 @@ "GetRegionDiskTypeRequest", "GetRegionHealthCheckRequest", "GetRegionHealthCheckServiceRequest", + "GetRegionHealthSourceRequest", "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupManagerResizeRequestRequest", "GetRegionInstanceGroupRequest", @@ -2442,6 +2489,7 @@ "GetRegionMultiMigRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", + "GetRegionNetworkPolicyRequest", "GetRegionNotificationEndpointRequest", "GetRegionOperationRequest", "GetRegionRequest", @@ -2490,6 +2538,7 @@ "GetTargetSslProxyRequest", "GetTargetTcpProxyRequest", "GetTargetVpnGatewayRequest", + "GetTrafficClassificationRuleRegionNetworkPolicyRequest", "GetUrlMapRequest", "GetVpnGatewayRequest", "GetVpnTunnelRequest", @@ -2520,6 +2569,10 @@ "HealthCheckServiceReference", "HealthCheckServicesList", "HealthChecksScopedList", + "HealthSource", + "HealthSourceAggregatedList", + "HealthSourceList", + "HealthSourcesScopedList", "HealthStatus", "HealthStatusForNetworkEndpoint", "Help", @@ -2544,6 +2597,7 @@ "Image", "ImageFamilyView", "ImageList", + "ImageParams", "InitialStateConfig", "InsertAddressRequest", "InsertAutoscalerRequest", @@ -2591,6 +2645,7 @@ "InsertRegionDiskRequest", "InsertRegionHealthCheckRequest", "InsertRegionHealthCheckServiceRequest", + "InsertRegionHealthSourceRequest", "InsertRegionInstanceGroupManagerRequest", "InsertRegionInstanceGroupManagerResizeRequestRequest", "InsertRegionInstanceTemplateRequest", @@ -2598,6 +2653,7 @@ "InsertRegionMultiMigRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", + "InsertRegionNetworkPolicyRequest", "InsertRegionNotificationEndpointRequest", "InsertRegionSecurityPolicyRequest", "InsertRegionSnapshotRequest", @@ -2888,6 +2944,7 @@ "ListRegionDiskTypesRequest", "ListRegionHealthCheckServicesRequest", "ListRegionHealthChecksRequest", + "ListRegionHealthSourcesRequest", "ListRegionInstanceGroupManagerResizeRequestsRequest", "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", @@ -2896,6 +2953,7 @@ "ListRegionMultiMigsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", + "ListRegionNetworkPoliciesRequest", "ListRegionNotificationEndpointsRequest", "ListRegionOperationsRequest", "ListRegionSecurityPoliciesRequest", @@ -3015,6 +3073,16 @@ "NetworkPeeringConnectionStatusConsensusState", "NetworkPeeringConnectionStatusTrafficConfiguration", "NetworkPerformanceConfig", + "NetworkPoliciesScopedList", + "NetworkPolicy", + "NetworkPolicyAggregatedList", + "NetworkPolicyAssociation", + "NetworkPolicyList", + "NetworkPolicyTrafficClassificationRule", + "NetworkPolicyTrafficClassificationRuleAction", + "NetworkPolicyTrafficClassificationRuleMatcher", + "NetworkPolicyTrafficClassificationRuleMatcherLayer4Config", + "NetworkPolicyTrafficClassificationRuleSecureTag", "NetworkProfile", "NetworkProfileLocation", "NetworkProfileNetworkFeatures", @@ -3109,8 +3177,10 @@ "PatchRegionDiskSettingRequest", "PatchRegionHealthCheckRequest", "PatchRegionHealthCheckServiceRequest", + "PatchRegionHealthSourceRequest", "PatchRegionInstanceGroupManagerRequest", "PatchRegionNetworkFirewallPolicyRequest", + "PatchRegionNetworkPolicyRequest", "PatchRegionSecurityPolicyRequest", "PatchRegionSnapshotSettingRequest", "PatchRegionSslPolicyRequest", @@ -3133,6 +3203,7 @@ "PatchTargetGrpcProxyRequest", "PatchTargetHttpProxyRequest", "PatchTargetHttpsProxyRequest", + "PatchTrafficClassificationRuleRegionNetworkPolicyRequest", "PatchUrlMapRequest", "PatchWireGroupRequest", "PathMatcher", @@ -3226,6 +3297,7 @@ "RemoveAssociationNetworkFirewallPolicyRequest", "RemoveAssociationOrganizationSecurityPolicyRequest", "RemoveAssociationRegionNetworkFirewallPolicyRequest", + "RemoveAssociationRegionNetworkPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", "RemoveInstanceTargetPoolRequest", @@ -3241,6 +3313,8 @@ "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "RemoveTrafficClassificationRuleRegionNetworkPolicyRequest", + "ReportFaultyReservationSubBlockRequest", "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "RequestRemovePeeringNetworkRequest", @@ -3265,6 +3339,8 @@ "ReservationSubBlockPhysicalTopology", "ReservationSubBlocksGetResponse", "ReservationSubBlocksListResponse", + "ReservationSubBlocksReportFaultyRequest", + "ReservationSubBlocksReportFaultyRequestFaultReason", "ResetInstanceRequest", "ResizeAdvancedInstanceGroupManagerRequest", "ResizeAdvancedRegionInstanceGroupManagerRequest", @@ -3511,6 +3587,7 @@ "Snapshot", "SnapshotAggregatedList", "SnapshotList", + "SnapshotParams", "SnapshotSettings", "SnapshotSettingsAccessLocation", "SnapshotSettingsAccessLocationAccessLocationPreference", @@ -3665,6 +3742,7 @@ "TestIamPermissionsRegionDiskRequest", "TestIamPermissionsRegionHealthCheckRequest", "TestIamPermissionsRegionHealthCheckServiceRequest", + "TestIamPermissionsRegionHealthSourceRequest", "TestIamPermissionsRegionInstanceGroupManagerRequest", "TestIamPermissionsRegionInstanceGroupRequest", "TestIamPermissionsRegionInstantSnapshotRequest", 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 06abc481cc2d..9ee42cc40c59 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 @@ -39,6 +39,7 @@ "AddAssociationNetworkFirewallPolicyRequest", "AddAssociationOrganizationSecurityPolicyRequest", "AddAssociationRegionNetworkFirewallPolicyRequest", + "AddAssociationRegionNetworkPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstanceTargetPoolRequest", "AddInstancesInstanceGroupRequest", @@ -58,6 +59,7 @@ "AddRuleSecurityPolicyRequest", "AddSignedUrlKeyBackendBucketRequest", "AddSignedUrlKeyBackendServiceRequest", + "AddTrafficClassificationRuleRegionNetworkPolicyRequest", "Address", "AddressAggregatedList", "AddressList", @@ -90,6 +92,8 @@ "AggregatedListPacketMirroringsRequest", "AggregatedListPublicDelegatedPrefixesRequest", "AggregatedListRegionCommitmentsRequest", + "AggregatedListRegionHealthSourcesRequest", + "AggregatedListRegionNetworkPoliciesRequest", "AggregatedListReservationsRequest", "AggregatedListResourcePoliciesRequest", "AggregatedListRoutersRequest", @@ -300,6 +304,7 @@ "DeleteRegionDiskRequest", "DeleteRegionHealthCheckRequest", "DeleteRegionHealthCheckServiceRequest", + "DeleteRegionHealthSourceRequest", "DeleteRegionInstanceGroupManagerRequest", "DeleteRegionInstanceGroupManagerResizeRequestRequest", "DeleteRegionInstanceTemplateRequest", @@ -307,6 +312,7 @@ "DeleteRegionMultiMigRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", + "DeleteRegionNetworkPolicyRequest", "DeleteRegionNotificationEndpointRequest", "DeleteRegionOperationRequest", "DeleteRegionOperationResponse", @@ -446,6 +452,7 @@ "GetAssociationNetworkFirewallPolicyRequest", "GetAssociationOrganizationSecurityPolicyRequest", "GetAssociationRegionNetworkFirewallPolicyRequest", + "GetAssociationRegionNetworkPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", "GetBackendServiceRequest", @@ -552,6 +559,7 @@ "GetRegionDiskTypeRequest", "GetRegionHealthCheckRequest", "GetRegionHealthCheckServiceRequest", + "GetRegionHealthSourceRequest", "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupManagerResizeRequestRequest", "GetRegionInstanceGroupRequest", @@ -560,6 +568,7 @@ "GetRegionMultiMigRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", + "GetRegionNetworkPolicyRequest", "GetRegionNotificationEndpointRequest", "GetRegionOperationRequest", "GetRegionRequest", @@ -608,6 +617,7 @@ "GetTargetSslProxyRequest", "GetTargetTcpProxyRequest", "GetTargetVpnGatewayRequest", + "GetTrafficClassificationRuleRegionNetworkPolicyRequest", "GetUrlMapRequest", "GetVpnGatewayRequest", "GetVpnTunnelRequest", @@ -639,6 +649,10 @@ "HealthCheckServicesList", "HealthChecksAggregatedList", "HealthChecksScopedList", + "HealthSource", + "HealthSourceAggregatedList", + "HealthSourceList", + "HealthSourcesScopedList", "HealthStatus", "HealthStatusForNetworkEndpoint", "Help", @@ -660,6 +674,7 @@ "Image", "ImageFamilyView", "ImageList", + "ImageParams", "InitialStateConfig", "InsertAddressRequest", "InsertAutoscalerRequest", @@ -707,6 +722,7 @@ "InsertRegionDiskRequest", "InsertRegionHealthCheckRequest", "InsertRegionHealthCheckServiceRequest", + "InsertRegionHealthSourceRequest", "InsertRegionInstanceGroupManagerRequest", "InsertRegionInstanceGroupManagerResizeRequestRequest", "InsertRegionInstanceTemplateRequest", @@ -714,6 +730,7 @@ "InsertRegionMultiMigRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", + "InsertRegionNetworkPolicyRequest", "InsertRegionNotificationEndpointRequest", "InsertRegionSecurityPolicyRequest", "InsertRegionSnapshotRequest", @@ -1004,6 +1021,7 @@ "ListRegionDisksRequest", "ListRegionHealthCheckServicesRequest", "ListRegionHealthChecksRequest", + "ListRegionHealthSourcesRequest", "ListRegionInstanceGroupManagerResizeRequestsRequest", "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", @@ -1012,6 +1030,7 @@ "ListRegionMultiMigsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", + "ListRegionNetworkPoliciesRequest", "ListRegionNotificationEndpointsRequest", "ListRegionOperationsRequest", "ListRegionSecurityPoliciesRequest", @@ -1131,6 +1150,16 @@ "NetworkPeeringConnectionStatusConsensusState", "NetworkPeeringConnectionStatusTrafficConfiguration", "NetworkPerformanceConfig", + "NetworkPoliciesScopedList", + "NetworkPolicy", + "NetworkPolicyAggregatedList", + "NetworkPolicyAssociation", + "NetworkPolicyList", + "NetworkPolicyTrafficClassificationRule", + "NetworkPolicyTrafficClassificationRuleAction", + "NetworkPolicyTrafficClassificationRuleMatcher", + "NetworkPolicyTrafficClassificationRuleMatcherLayer4Config", + "NetworkPolicyTrafficClassificationRuleSecureTag", "NetworkProfile", "NetworkProfileLocation", "NetworkProfileNetworkFeatures", @@ -1225,8 +1254,10 @@ "PatchRegionDiskSettingRequest", "PatchRegionHealthCheckRequest", "PatchRegionHealthCheckServiceRequest", + "PatchRegionHealthSourceRequest", "PatchRegionInstanceGroupManagerRequest", "PatchRegionNetworkFirewallPolicyRequest", + "PatchRegionNetworkPolicyRequest", "PatchRegionSecurityPolicyRequest", "PatchRegionSnapshotSettingRequest", "PatchRegionSslPolicyRequest", @@ -1249,6 +1280,7 @@ "PatchTargetGrpcProxyRequest", "PatchTargetHttpProxyRequest", "PatchTargetHttpsProxyRequest", + "PatchTrafficClassificationRuleRegionNetworkPolicyRequest", "PatchUrlMapRequest", "PatchWireGroupRequest", "PathMatcher", @@ -1342,6 +1374,7 @@ "RemoveAssociationNetworkFirewallPolicyRequest", "RemoveAssociationOrganizationSecurityPolicyRequest", "RemoveAssociationRegionNetworkFirewallPolicyRequest", + "RemoveAssociationRegionNetworkPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstanceTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", @@ -1357,6 +1390,8 @@ "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "RemoveTrafficClassificationRuleRegionNetworkPolicyRequest", + "ReportFaultyReservationSubBlockRequest", "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "RequestRemovePeeringNetworkRequest", @@ -1377,6 +1412,8 @@ "ReservationSubBlockPhysicalTopology", "ReservationSubBlocksGetResponse", "ReservationSubBlocksListResponse", + "ReservationSubBlocksReportFaultyRequest", + "ReservationSubBlocksReportFaultyRequestFaultReason", "ReservationsBlocksPerformMaintenanceRequest", "ReservationsPerformMaintenanceRequest", "ReservationsResizeRequest", @@ -1628,6 +1665,7 @@ "Snapshot", "SnapshotAggregatedList", "SnapshotList", + "SnapshotParams", "SnapshotSettings", "SnapshotSettingsAccessLocation", "SnapshotSettingsAccessLocationAccessLocationPreference", @@ -1781,6 +1819,7 @@ "TestIamPermissionsRegionDiskRequest", "TestIamPermissionsRegionHealthCheckRequest", "TestIamPermissionsRegionHealthCheckServiceRequest", + "TestIamPermissionsRegionHealthSourceRequest", "TestIamPermissionsRegionInstanceGroupManagerRequest", "TestIamPermissionsRegionInstanceGroupRequest", "TestIamPermissionsRegionInstantSnapshotRequest", @@ -3005,6 +3044,67 @@ class AddAssociationRegionNetworkFirewallPolicyRequest(proto.Message): ) +class AddAssociationRegionNetworkPolicyRequest(proto.Message): + r"""A request message for RegionNetworkPolicies.AddAssociation. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_policy (str): + Name of the network policy resource to + update. + network_policy_association_resource (google.cloud.compute_v1beta.types.NetworkPolicyAssociation): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region of 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_policy: str = proto.Field( + proto.STRING, + number=504961123, + ) + network_policy_association_resource: "NetworkPolicyAssociation" = proto.Field( + proto.MESSAGE, + number=84002920, + message="NetworkPolicyAssociation", + ) + 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, + ) + + class AddHealthCheckTargetPoolRequest(proto.Message): r"""A request message for TargetPools.AddHealthCheck. See the method description for details. @@ -4134,6 +4234,68 @@ class AddSignedUrlKeyBackendServiceRequest(proto.Message): ) +class AddTrafficClassificationRuleRegionNetworkPolicyRequest(proto.Message): + r"""A request message for + RegionNetworkPolicies.AddTrafficClassificationRule. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_policy (str): + Name of the network policy resource to + update. + network_policy_traffic_classification_rule_resource (google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region of 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_policy: str = proto.Field( + proto.STRING, + number=504961123, + ) + network_policy_traffic_classification_rule_resource: "NetworkPolicyTrafficClassificationRule" = proto.Field( + proto.MESSAGE, + number=464294582, + message="NetworkPolicyTrafficClassificationRule", + ) + 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, + ) + + class Address(proto.Message): r"""Represents an IP Address resource. Google Compute Engine has two IP Address resources: \* `Global (external and @@ -4172,6 +4334,21 @@ class Address(proto.Message): identifier is defined by the server. This field is a member of `oneof`_ ``_id``. + ip_collection (str): + Reference to the source of external IPv4 + addresses, like a PublicDelegatedPrefix (PDP) + for BYOIP. The PDP must support enhanced IPv4 + allocations. Use one of the following formats to + specify a PDP when reserving an external IPv4 + address using BYOIP. - Full resource URL, as in + https://www.googleapis.com/compute/v1/projects/projectId/regions/region + /publicDelegatedPrefixes/pdp-name - Partial URL, + as in - + projects/projectId/regions/region/publicDelegatedPrefixes/pdp-name + - + regions/region/publicDelegatedPrefixes/pdp-name + + This field is a member of `oneof`_ ``_ip_collection``. ip_version (str): The IP version that will be used by this address. Valid options are IPV4 or IPV6. Check @@ -4511,6 +4688,11 @@ class Status(proto.Enum): number=3355, optional=True, ) + ip_collection: str = proto.Field( + proto.STRING, + number=176818358, + optional=True, + ) ip_version: str = proto.Field( proto.STRING, number=294959552, @@ -9039,162 +9221,8 @@ class AggregatedListRegionCommitmentsRequest(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 on - resource 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 - Google RE2 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. @@ -9287,7 +9315,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 @@ -9347,9 +9375,9 @@ class AggregatedListResourcePoliciesRequest(proto.Message): ) -class AggregatedListRoutersRequest(proto.Message): - r"""A request message for Routers.AggregatedList. See the method - description for details. +class AggregatedListRegionNetworkPoliciesRequest(proto.Message): + r"""A request message for RegionNetworkPolicies.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -9501,9 +9529,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 @@ -9595,7 +9623,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 @@ -9655,8 +9683,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. @@ -9749,7 +9777,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 @@ -9809,9 +9837,9 @@ class AggregatedListServiceAttachmentsRequest(proto.Message): ) -class AggregatedListSnapshotsRequest(proto.Message): - r"""A request message for Snapshots.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 @@ -9963,9 +9991,9 @@ class AggregatedListSnapshotsRequest(proto.Message): ) -class AggregatedListSslCertificatesRequest(proto.Message): - r"""A request message for SslCertificates.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 @@ -10117,9 +10145,9 @@ class AggregatedListSslCertificatesRequest(proto.Message): ) -class AggregatedListSslPoliciesRequest(proto.Message): - r"""A request message for SslPolicies.AggregatedList. See the - method description for details. +class AggregatedListServiceAttachmentsRequest(proto.Message): + r"""A request message for ServiceAttachments.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -10271,9 +10299,9 @@ class AggregatedListSslPoliciesRequest(proto.Message): ) -class AggregatedListStoragePoolTypesRequest(proto.Message): - r"""A request message for StoragePoolTypes.AggregatedList. See - the method description for details. +class AggregatedListSnapshotsRequest(proto.Message): + r"""A request message for Snapshots.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -10425,8 +10453,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. @@ -10519,7 +10547,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 @@ -10579,8 +10607,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. @@ -10673,7 +10701,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 @@ -10733,8 +10761,8 @@ class AggregatedListSubnetworksRequest(proto.Message): ) -class AggregatedListTargetHttpProxiesRequest(proto.Message): - r"""A request message for TargetHttpProxies.AggregatedList. See +class AggregatedListStoragePoolTypesRequest(proto.Message): + r"""A request message for StoragePoolTypes.AggregatedList. See the method description for details. @@ -10827,7 +10855,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 @@ -10887,9 +10915,9 @@ class AggregatedListTargetHttpProxiesRequest(proto.Message): ) -class AggregatedListTargetHttpsProxiesRequest(proto.Message): - r"""A request message for TargetHttpsProxies.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 @@ -10981,7 +11009,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 @@ -11041,8 +11069,8 @@ class AggregatedListTargetHttpsProxiesRequest(proto.Message): ) -class AggregatedListTargetInstancesRequest(proto.Message): - r"""A request message for TargetInstances.AggregatedList. See the +class AggregatedListSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.AggregatedList. See the method description for details. @@ -11195,9 +11223,9 @@ class AggregatedListTargetInstancesRequest(proto.Message): ) -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 @@ -11289,7 +11317,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 @@ -11349,8 +11377,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. @@ -11503,9 +11531,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 @@ -11657,9 +11685,163 @@ 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 + + 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 on + resource 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 + Google RE2 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 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 @@ -11811,9 +11993,317 @@ class AggregatedListUrlMapsRequest(proto.Message): ) -class AggregatedListVpnGatewaysRequest(proto.Message): - r"""A request message for VpnGateways.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 on + resource 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 + Google RE2 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 on + resource 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 + Google RE2 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 @@ -26037,6 +26527,59 @@ class DeleteRegionHealthCheckServiceRequest(proto.Message): ) +class DeleteRegionHealthSourceRequest(proto.Message): + r"""A request message for RegionHealthSources.Delete. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + health_source (str): + Name of the HealthSource resource to delete. + project (str): + Project ID for this request. + region (str): + Name of the region scoping 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``. + """ + + health_source: str = proto.Field( + proto.STRING, + number=376521566, + ) + 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, + ) + + class DeleteRegionInstanceGroupManagerRequest(proto.Message): r"""A request message for RegionInstanceGroupManagers.Delete. See the method description for details. @@ -26423,21 +26966,21 @@ class DeleteRegionNetworkFirewallPolicyRequest(proto.Message): ) -class DeleteRegionNotificationEndpointRequest(proto.Message): - r"""A request message for RegionNotificationEndpoints.Delete. See - the method description for details. +class DeleteRegionNetworkPolicyRequest(proto.Message): + r"""A request message for RegionNetworkPolicies.Delete. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - notification_endpoint (str): - Name of the NotificationEndpoint resource to + network_policy (str): + Name of the network policy resource to delete. project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region of this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -26458,9 +27001,9 @@ class DeleteRegionNotificationEndpointRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - notification_endpoint: str = proto.Field( + network_policy: str = proto.Field( proto.STRING, - number=376807017, + number=504961123, ) project: str = proto.Field( proto.STRING, @@ -26477,49 +27020,17 @@ class DeleteRegionNotificationEndpointRequest(proto.Message): ) -class DeleteRegionOperationRequest(proto.Message): - r"""A request message for RegionOperations.Delete. See the method - description for details. - - Attributes: - operation (str): - Name of the Operations resource to delete, or - its unique numeric identifier. - project (str): - Project ID for this request. - region (str): - Name of the region for this request. - """ - - operation: str = proto.Field( - proto.STRING, - number=52090215, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - - -class DeleteRegionOperationResponse(proto.Message): - r"""A response message for RegionOperations.Delete. See the - method description for details. - - """ - - -class DeleteRegionSecurityPolicyRequest(proto.Message): - r"""A request message for RegionSecurityPolicies.Delete. See the - method description for details. +class DeleteRegionNotificationEndpointRequest(proto.Message): + r"""A request message for RegionNotificationEndpoints.Delete. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + notification_endpoint (str): + Name of the NotificationEndpoint resource to + delete. project (str): Project ID for this request. region (str): @@ -26542,10 +27053,12 @@ class DeleteRegionSecurityPolicyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - security_policy (str): - Name of the security policy to delete. """ + notification_endpoint: str = proto.Field( + proto.STRING, + number=376807017, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -26559,100 +27072,26 @@ class DeleteRegionSecurityPolicyRequest(proto.Message): number=37109963, optional=True, ) - security_policy: str = proto.Field( - proto.STRING, - number=171082513, - ) -class DeleteRegionSnapshotRequest(proto.Message): - r"""A request message for RegionSnapshots.Delete. See the method +class DeleteRegionOperationRequest(proto.Message): + r"""A request message for RegionOperations.Delete. See the method description for details. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - Attributes: + operation (str): + Name of the Operations resource to delete, or + its unique numeric identifier. project (str): Project ID for this request. region (str): - The 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``. - snapshot (str): - Name of the snapshot resource to delete. + Name of the region for this request. """ - 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, - ) - snapshot: str = proto.Field( + operation: str = proto.Field( proto.STRING, - number=284874180, + number=52090215, ) - - -class DeleteRegionSslCertificateRequest(proto.Message): - r"""A request message for RegionSslCertificates.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 scoping 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``. - ssl_certificate (str): - Name of the SslCertificate resource to - delete. - """ - project: str = proto.Field( proto.STRING, number=227560217, @@ -26661,74 +27100,232 @@ class DeleteRegionSslCertificateRequest(proto.Message): proto.STRING, number=138946292, ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - ssl_certificate: str = proto.Field( - proto.STRING, - number=46443492, - ) -class DeleteRegionSslPolicyRequest(proto.Message): - r"""A request message for RegionSslPolicies.Delete. See the +class DeleteRegionOperationResponse(proto.Message): + r"""A response message for RegionOperations.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 scoping 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``. - ssl_policy (str): - Name of the SSL policy to delete. The name - must be 1-63 characters long, and comply with - RFC1035. """ - 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, - ) - ssl_policy: str = proto.Field( - proto.STRING, - number=295190213, - ) - -class DeleteRegionTargetHttpProxyRequest(proto.Message): - r"""A request message for RegionTargetHttpProxies.Delete. See the +class DeleteRegionSecurityPolicyRequest(proto.Message): + r"""A request message for RegionSecurityPolicies.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 scoping 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``. + security_policy (str): + Name of the security policy to delete. + """ + + 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, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + + +class DeleteRegionSnapshotRequest(proto.Message): + r"""A request message for RegionSnapshots.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): + The 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``. + snapshot (str): + Name of the snapshot resource to delete. + """ + + 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, + ) + snapshot: str = proto.Field( + proto.STRING, + number=284874180, + ) + + +class DeleteRegionSslCertificateRequest(proto.Message): + r"""A request message for RegionSslCertificates.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 scoping 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``. + ssl_certificate (str): + Name of the SslCertificate resource to + delete. + """ + + 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, + ) + ssl_certificate: str = proto.Field( + proto.STRING, + number=46443492, + ) + + +class DeleteRegionSslPolicyRequest(proto.Message): + r"""A request message for RegionSslPolicies.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 scoping 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``. + ssl_policy (str): + Name of the SSL policy to delete. The name + must be 1-63 characters long, and comply with + RFC1035. + """ + + 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, + ) + ssl_policy: str = proto.Field( + proto.STRING, + number=295190213, + ) + + +class DeleteRegionTargetHttpProxyRequest(proto.Message): + r"""A request message for RegionTargetHttpProxies.Delete. See the method description for details. @@ -36677,6 +37274,47 @@ class GetAssociationRegionNetworkFirewallPolicyRequest(proto.Message): ) +class GetAssociationRegionNetworkPolicyRequest(proto.Message): + r"""A request message for RegionNetworkPolicies.GetAssociation. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The name of the association to get from the + network policy. + + This field is a member of `oneof`_ ``_name``. + network_policy (str): + Name of the network policy to which the + queried association belongs. + project (str): + Project ID for this request. + region (str): + Name of the region of this request. + """ + + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + network_policy: str = proto.Field( + proto.STRING, + number=504961123, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetAutoscalerRequest(proto.Message): r"""A request message for Autoscalers.Get. See the method description for details. @@ -39870,6 +40508,33 @@ class GetRegionHealthCheckServiceRequest(proto.Message): ) +class GetRegionHealthSourceRequest(proto.Message): + r"""A request message for RegionHealthSources.Get. See the method + description for details. + + Attributes: + health_source (str): + Name of the HealthSource resource to return. + project (str): + Project ID for this request. + region (str): + Name of the region scoping this request. + """ + + health_source: str = proto.Field( + proto.STRING, + number=376521566, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetRegionInstanceGroupManagerRequest(proto.Message): r"""A request message for RegionInstanceGroupManagers.Get. See the method description for details. @@ -40135,6 +40800,34 @@ class GetRegionNetworkFirewallPolicyRequest(proto.Message): ) +class GetRegionNetworkPolicyRequest(proto.Message): + r"""A request message for RegionNetworkPolicies.Get. See the + method description for details. + + Attributes: + network_policy (str): + Name of the network policy resource to + return. + project (str): + Project ID for this request. + region (str): + Name of the region of this request. + """ + + network_policy: str = proto.Field( + proto.STRING, + number=504961123, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetRegionNotificationEndpointRequest(proto.Message): r"""A request message for RegionNotificationEndpoints.Get. See the method description for details. @@ -41568,6 +42261,48 @@ class GetTargetVpnGatewayRequest(proto.Message): ) +class GetTrafficClassificationRuleRegionNetworkPolicyRequest(proto.Message): + r"""A request message for + RegionNetworkPolicies.GetTrafficClassificationRule. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_policy (str): + Name of the network policy to which the + queried rule belongs. + priority (int): + The priority of the rule to get from the + network policy. + + This field is a member of `oneof`_ ``_priority``. + project (str): + Project ID for this request. + region (str): + Name of the region of this request. + """ + + network_policy: str = proto.Field( + proto.STRING, + number=504961123, + ) + priority: int = proto.Field( + proto.INT32, + number=445151652, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetUrlMapRequest(proto.Message): r"""A request message for UrlMaps.Get. See the method description for details. @@ -43774,6 +44509,353 @@ class HealthChecksScopedList(proto.Message): ) +class HealthSource(proto.Message): + r"""Represents a health source. A health source resource + specifies the source resources and the health aggregation policy + applied to the source resources to determine the aggregated + health status. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 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``. + fingerprint (str): + Fingerprint of this resource. A hash of the + contents stored in this object. This field is + used in optimistic locking. This field will be + ignored when inserting a HealthSource. An + up-to-date fingerprint must be provided in order + to patch the HealthSource; Otherwise, the + request will fail with error 412 + conditionNotMet. To see the latest fingerprint, + make a get() request to retrieve the + HealthSource. + + This field is a member of `oneof`_ ``_fingerprint``. + health_aggregation_policy (str): + URL to the HealthAggregationPolicy resource. + Must be set. Must be regional and in the same + region as the HealthSource. Can be mutated. + + This field is a member of `oneof`_ ``_health_aggregation_policy``. + id (int): + [Output Only] A unique identifier for this resource type. + The server generates this identifier. + + This field is a member of `oneof`_ ``_id``. + kind (str): + [Output Only] Type of the resource. Always + compute#healthSource for health sources. + + 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 with RFC1035. 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``. + region (str): + [Output Only] URL of the region where the health source + resides. This field applies only to the regional resource. + You must specify this field as part of the HTTP request URL. + It is not settable as a field in the request body. + + This field is a member of `oneof`_ ``_region``. + self_link (str): + [Output Only] Server-defined URL for the resource. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + [Output Only] Server-defined URL with id for the resource. + + This field is a member of `oneof`_ ``_self_link_with_id``. + source_type (str): + Specifies the type of the HealthSource. The only allowed + value is BACKEND_SERVICE. Must be specified when the + HealthSource is created, and cannot be mutated. Check the + SourceType enum for the list of possible values. + + This field is a member of `oneof`_ ``_source_type``. + sources (MutableSequence[str]): + URLs to the source resources. Must be size 1. Must be a + BackendService if the sourceType is BACKEND_SERVICE. The + BackendService must have load balancing scheme INTERNAL or + INTERNAL_MANAGED and must be regional and in the same region + as the HealthSource (cross-region deployment for + INTERNAL_MANAGED is not supported). The BackendService may + use only IGs, MIGs, or NEGs of type GCE_VM_IP or + GCE_VM_IP_PORT. The BackendService may not use haPolicy. Can + be mutated. + """ + + class SourceType(proto.Enum): + r"""Specifies the type of the HealthSource. The only allowed value is + BACKEND_SERVICE. Must be specified when the HealthSource is created, + and cannot be mutated. + + Values: + UNDEFINED_SOURCE_TYPE (0): + A value indicating that the enum field is not + set. + BACKEND_SERVICE (285792202): + No description available. + """ + UNDEFINED_SOURCE_TYPE = 0 + BACKEND_SERVICE = 285792202 + + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + fingerprint: str = proto.Field( + proto.STRING, + number=234678500, + optional=True, + ) + health_aggregation_policy: str = proto.Field( + proto.STRING, + number=240314354, + 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, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + 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, + ) + source_type: str = proto.Field( + proto.STRING, + number=452245726, + optional=True, + ) + sources: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=125606840, + ) + + +class HealthSourceAggregatedList(proto.Message): + r"""Contains a list of HealthSourcesScopedList. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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_v1beta.types.HealthSourcesScopedList]): + A list of HealthSourcesScopedList resources. + kind (str): + 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 than maxResults, 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] Server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + warning (google.cloud.compute_v1beta.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableMapping[str, "HealthSourcesScopedList"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=100526016, + message="HealthSourcesScopedList", + ) + 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, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + +class HealthSourceList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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_v1beta.types.HealthSource]): + A list of HealthSource resources. + kind (str): + [Output Only] Type of the resource. Always + compute#healthSource for health sources. + + 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 than maxResults, 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] Server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + warning (google.cloud.compute_v1beta.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["HealthSource"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="HealthSource", + ) + 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, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + +class HealthSourcesScopedList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + health_sources (MutableSequence[google.cloud.compute_v1beta.types.HealthSource]): + A list of HealthSources contained in this + scope. + warning (google.cloud.compute_v1beta.types.Warning): + Informational warning which replaces the list + of health sources when the list is empty. + + This field is a member of `oneof`_ ``_warning``. + """ + + health_sources: MutableSequence["HealthSource"] = proto.RepeatedField( + proto.MESSAGE, + number=397879509, + message="HealthSource", + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class HealthStatus(proto.Message): r""" @@ -45468,6 +46550,11 @@ class Image(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + params (google.cloud.compute_v1beta.types.ImageParams): + Input only. [Input Only] Additional params passed with the + request, but not persisted as part of resource payload. + + This field is a member of `oneof`_ ``_params``. raw_disk (google.cloud.compute_v1beta.types.RawDisk): The parameters of the raw disk image. @@ -45759,6 +46846,12 @@ class Status(proto.Enum): number=3373707, optional=True, ) + params: "ImageParams" = proto.Field( + proto.MESSAGE, + number=78313862, + optional=True, + message="ImageParams", + ) raw_disk: "RawDisk" = proto.Field( proto.MESSAGE, number=503113556, @@ -45955,6 +47048,25 @@ def raw_page(self): ) +class ImageParams(proto.Message): + r"""Additional image params. + + Attributes: + resource_manager_tags (MutableMapping[str, str]): + Resource manager tags to be bound to the image. 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: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=377671164, + ) + + class InitialStateConfig(proto.Message): r"""Initial State for shielded instance, these are public keys which are safe to store in public @@ -48474,6 +49586,60 @@ class InsertRegionHealthCheckServiceRequest(proto.Message): ) +class InsertRegionHealthSourceRequest(proto.Message): + r"""A request message for RegionHealthSources.Insert. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + health_source_resource (google.cloud.compute_v1beta.types.HealthSource): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region scoping 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``. + """ + + health_source_resource: "HealthSource" = proto.Field( + proto.MESSAGE, + number=357735375, + message="HealthSource", + ) + 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, + ) + + class InsertRegionInstanceGroupManagerRequest(proto.Message): r"""A request message for RegionInstanceGroupManagers.Insert. See the method description for details. @@ -48864,6 +50030,60 @@ class InsertRegionNetworkFirewallPolicyRequest(proto.Message): ) +class InsertRegionNetworkPolicyRequest(proto.Message): + r"""A request message for RegionNetworkPolicies.Insert. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_policy_resource (google.cloud.compute_v1beta.types.NetworkPolicy): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region of 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_policy_resource: "NetworkPolicy" = proto.Field( + proto.MESSAGE, + number=437886058, + message="NetworkPolicy", + ) + 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, + ) + + class InsertRegionNotificationEndpointRequest(proto.Message): r"""A request message for RegionNotificationEndpoints.Insert. See the method description for details. @@ -57543,6 +58763,13 @@ class Interconnect(proto.Message): possible values. This field is a member of `oneof`_ ``_state``. + subzone (str): + Specific subzone in the InterconnectLocation + that represents where this connection is to be + provisioned. Check the Subzone enum for the list + of possible values. + + This field is a member of `oneof`_ ``_subzone``. wire_groups (MutableSequence[str]): [Output Only] A list of the URLs of all CrossSiteNetwork WireGroups configured to use this Interconnect. The @@ -57676,6 +58903,23 @@ class State(proto.Enum): ACTIVE = 314733318 UNPROVISIONED = 517333979 + class Subzone(proto.Enum): + r"""Specific subzone in the InterconnectLocation that represents + where this connection is to be provisioned. + + Values: + UNDEFINED_SUBZONE (0): + A value indicating that the enum field is not + set. + SUBZONE_A (291575438): + Subzone A. + SUBZONE_B (291575439): + Subzone B. + """ + UNDEFINED_SUBZONE = 0 + SUBZONE_A = 291575438 + SUBZONE_B = 291575439 + aai_enabled: bool = proto.Field( proto.BOOL, number=388780363, @@ -57843,6 +59087,11 @@ class State(proto.Enum): number=109757585, optional=True, ) + subzone: str = proto.Field( + proto.STRING, + number=280084972, + optional=True, + ) wire_groups: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=40662734, @@ -74041,10 +75290,9 @@ class ListRegionHealthChecksRequest(proto.Message): ) -class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): - r"""A request message for - RegionInstanceGroupManagerResizeRequests.List. See the method - description for details. +class ListRegionHealthSourcesRequest(proto.Message): + r"""A request message for RegionHealthSources.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -74094,9 +75342,6 @@ class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. - instance_group_manager (str): - The name of the managed instance group. The - name should conform to RFC1035. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -74128,8 +75373,7 @@ class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. Name - should conform to RFC1035. + 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 @@ -74147,10 +75391,6 @@ class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): number=336120696, optional=True, ) - instance_group_manager: str = proto.Field( - proto.STRING, - number=249363395, - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -74181,9 +75421,10 @@ class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): ) -class ListRegionInstanceGroupManagersRequest(proto.Message): - r"""A request message for RegionInstanceGroupManagers.List. See - the method description for details. +class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): + r"""A request message for + RegionInstanceGroupManagerResizeRequests.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -74233,6 +75474,9 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. + instance_group_manager (str): + The name of the managed instance group. The + name should conform to RFC1035. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -74264,7 +75508,8 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region scoping this request. Name + should conform to RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -74282,6 +75527,10 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): number=336120696, optional=True, ) + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -74312,9 +75561,9 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): ) -class ListRegionInstanceGroupsRequest(proto.Message): - r"""A request message for RegionInstanceGroups.List. See the - method description for details. +class ListRegionInstanceGroupManagersRequest(proto.Message): + r"""A request message for RegionInstanceGroupManagers.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -74443,8 +75692,8 @@ class ListRegionInstanceGroupsRequest(proto.Message): ) -class ListRegionInstanceTemplatesRequest(proto.Message): - r"""A request message for RegionInstanceTemplates.List. See the +class ListRegionInstanceGroupsRequest(proto.Message): + r"""A request message for RegionInstanceGroups.List. See the method description for details. @@ -74526,7 +75775,7 @@ class ListRegionInstanceTemplatesRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the regions for this request. + 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 @@ -74537,34 +75786,8 @@ class ListRegionInstanceTemplatesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - view (str): - View of the instance template. - Check the View enum for the list of possible - values. - - This field is a member of `oneof`_ ``_view``. """ - class View(proto.Enum): - r"""View of the instance template. - - Values: - UNDEFINED_VIEW (0): - A value indicating that the enum field is not - set. - BASIC (62970894): - Include everything except Partner Metadata. - FULL (2169487): - Include everything. - INSTANCE_VIEW_UNSPECIFIED (8444647): - The default / unset value. The API will - default to the BASIC view. - """ - UNDEFINED_VIEW = 0 - BASIC = 62970894 - FULL = 2169487 - INSTANCE_VIEW_UNSPECIFIED = 8444647 - filter: str = proto.Field( proto.STRING, number=336120696, @@ -74598,15 +75821,10 @@ class View(proto.Enum): number=517198390, optional=True, ) - view: str = proto.Field( - proto.STRING, - number=3619493, - optional=True, - ) -class ListRegionInstantSnapshotsRequest(proto.Message): - r"""A request message for RegionInstantSnapshots.List. See the +class ListRegionInstanceTemplatesRequest(proto.Message): + r"""A request message for RegionInstanceTemplates.List. See the method description for details. @@ -74688,7 +75906,7 @@ class ListRegionInstantSnapshotsRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the region for this request. + The name of the regions for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -74699,8 +75917,34 @@ class ListRegionInstantSnapshotsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + view (str): + View of the instance template. + Check the View enum for the list of possible + values. + + This field is a member of `oneof`_ ``_view``. """ + class View(proto.Enum): + r"""View of the instance template. + + Values: + UNDEFINED_VIEW (0): + A value indicating that the enum field is not + set. + BASIC (62970894): + Include everything except Partner Metadata. + FULL (2169487): + Include everything. + INSTANCE_VIEW_UNSPECIFIED (8444647): + The default / unset value. The API will + default to the BASIC view. + """ + UNDEFINED_VIEW = 0 + BASIC = 62970894 + FULL = 2169487 + INSTANCE_VIEW_UNSPECIFIED = 8444647 + filter: str = proto.Field( proto.STRING, number=336120696, @@ -74734,11 +75978,16 @@ class ListRegionInstantSnapshotsRequest(proto.Message): number=517198390, optional=True, ) + view: str = proto.Field( + proto.STRING, + number=3619493, + optional=True, + ) -class ListRegionMultiMigsRequest(proto.Message): - r"""A request message for RegionMultiMigs.List. See the method - description for details. +class ListRegionInstantSnapshotsRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -74819,7 +76068,7 @@ class ListRegionMultiMigsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + The 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 @@ -74867,9 +76116,140 @@ class ListRegionMultiMigsRequest(proto.Message): ) -class ListRegionNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for RegionNetworkEndpointGroups.List. See - the method description for details. +class ListRegionMultiMigsRequest(proto.Message): + r"""A request message for RegionMultiMigs.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 on + resource 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 + Google RE2 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 + 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 ListRegionNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for RegionNetworkEndpointGroups.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -75131,6 +76511,137 @@ class ListRegionNetworkFirewallPoliciesRequest(proto.Message): ) +class ListRegionNetworkPoliciesRequest(proto.Message): + r"""A request message for RegionNetworkPolicies.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 on + resource 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 + Google RE2 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 of 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, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + class ListRegionNotificationEndpointsRequest(proto.Message): r"""A request message for RegionNotificationEndpoints.List. See the method description for details. @@ -86886,6 +88397,691 @@ class TotalEgressBandwidthTier(proto.Enum): ) +class NetworkPoliciesScopedList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_policies (MutableSequence[google.cloud.compute_v1beta.types.NetworkPolicy]): + A list of network policies contained in this + scope. + warning (google.cloud.compute_v1beta.types.Warning): + Informational warning which replaces the list + of network policies when the list is empty. + + This field is a member of `oneof`_ ``_warning``. + """ + + network_policies: MutableSequence["NetworkPolicy"] = proto.RepeatedField( + proto.MESSAGE, + number=473193537, + message="NetworkPolicy", + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + +class NetworkPolicy(proto.Message): + r"""Represents a Network Policy resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + associations (MutableSequence[google.cloud.compute_v1beta.types.NetworkPolicyAssociation]): + [Output Only] A list of associations that belong to this + network policy. + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 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] 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] Type of the resource. Always + compute#networkPolicy for network policies + + This field is a member of `oneof`_ ``_kind``. + name (str): + Name of the resource. + + This field is a member of `oneof`_ ``_name``. + region (str): + [Output Only] URL of the region where the regional network + policy resides. You must specify this field as part of the + HTTP request URL. It is not settable as a field in the + request body. + + This field is a member of `oneof`_ ``_region``. + rule_tuple_count (int): + [Output Only] Total count of all network policy rule tuples. + A network policy can not exceed a set number of tuples. + + This field is a member of `oneof`_ ``_rule_tuple_count``. + self_link (str): + [Output Only] Server-defined URL for the resource. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + [Output Only] Server-defined URL for this resource with the + resource id. + + This field is a member of `oneof`_ ``_self_link_with_id``. + traffic_classification_rules (MutableSequence[google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule]): + [Output Only] A list of traffic classification rules that + belong to this policy. + """ + + associations: MutableSequence["NetworkPolicyAssociation"] = proto.RepeatedField( + proto.MESSAGE, + number=508736530, + message="NetworkPolicyAssociation", + ) + 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, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + optional=True, + ) + rule_tuple_count: int = proto.Field( + proto.INT32, + number=388342037, + 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, + ) + traffic_classification_rules: MutableSequence[ + "NetworkPolicyTrafficClassificationRule" + ] = proto.RepeatedField( + proto.MESSAGE, + number=291759200, + message="NetworkPolicyTrafficClassificationRule", + ) + + +class NetworkPolicyAggregatedList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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_v1beta.types.NetworkPoliciesScopedList]): + A list of NetworkPoliciesScopedList + resources. + kind (str): + [Output Only] Type of resource. Always + compute#networkPolicyAggregatedList for lists of network + policies. + + 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 than maxResults, 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] Server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + [Output Only] Unreachable resources. + warning (google.cloud.compute_v1beta.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableMapping[str, "NetworkPoliciesScopedList"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=100526016, + message="NetworkPoliciesScopedList", + ) + 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 NetworkPolicyAssociation(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + attachment_target (str): + The target that the network policy is + attached to. + + This field is a member of `oneof`_ ``_attachment_target``. + name (str): + The name for an association. + + This field is a member of `oneof`_ ``_name``. + """ + + attachment_target: str = proto.Field( + proto.STRING, + number=175773741, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + + +class NetworkPolicyList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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_v1beta.types.NetworkPolicy]): + A list of NetworkPolicy resources. + kind (str): + [Output Only] Type of resource. Always + compute#networkPolicyList for lists of network policies. + + 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 than maxResults, 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``. + warning (google.cloud.compute_v1beta.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["NetworkPolicy"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="NetworkPolicy", + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + +class NetworkPolicyTrafficClassificationRule(proto.Message): + r"""Represents a traffic classification rule that describes one + or more match conditions along with the action to be taken when + traffic matches this condition. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + action (google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRuleAction): + The Action to perform when the client + connection triggers the rule. + + This field is a member of `oneof`_ ``_action``. + description (str): + An optional description for this resource. + + This field is a member of `oneof`_ ``_description``. + disabled (bool): + Denotes whether the network policy rule is + disabled. When set to true, the network policy + rule is not enforced and traffic behaves as if + it did not exist. If this is unspecified, the + network policy rule will be enabled. + + This field is a member of `oneof`_ ``_disabled``. + kind (str): + [Output only] Type of the resource. Always + compute#networkPolicyTrafficClassificationRule for network + policy traffic classification rules + + This field is a member of `oneof`_ ``_kind``. + match (google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRuleMatcher): + A match condition that outgoing traffic is + evaluated against. If it evaluates to true, the + corresponding 'action' is enforced. + + This field is a member of `oneof`_ ``_match``. + priority (int): + An integer indicating the priority of a rule + in the list. The priority must be a positive + value between 1 and 2147482647. The priority + values from 2147482648 to 2147483647 (1000) are + reserved for system default network policy + rules. Rules are evaluated from highest to + lowest priority where 1 is the highest priority + and 2147483647 is the lowest priority. + + This field is a member of `oneof`_ ``_priority``. + rule_name (str): + An optional name for the rule. This field is + not a unique identifier and can be updated. + + This field is a member of `oneof`_ ``_rule_name``. + rule_tuple_count (int): + [Output Only] Calculation of the complexity of a single + network policy rule. + + This field is a member of `oneof`_ ``_rule_tuple_count``. + target_secure_tags (MutableSequence[google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRuleSecureTag]): + A list of secure tags that controls which + instances the traffic classification rule + applies to. If targetSecureTag are specified, + then the traffic classification rule applies + only to instances in the VPC network that have + one of those EFFECTIVE secure tags, if all the + targetSecureTag are in INEFFECTIVE state, then + this rule will be ignored. targetSecureTag may + not be set at the same time as + targetServiceAccounts. If neither + targetServiceAccounts nor targetSecureTag are + specified, the traffic classification rule + applies to all instances on the specified + network. Maximum number of target label tags + allowed is 256. + target_service_accounts (MutableSequence[str]): + A list of service accounts indicating the + sets of instances that are applied with this + rule. + """ + + action: "NetworkPolicyTrafficClassificationRuleAction" = proto.Field( + proto.MESSAGE, + number=187661878, + optional=True, + message="NetworkPolicyTrafficClassificationRuleAction", + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=270940796, + optional=True, + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + match: "NetworkPolicyTrafficClassificationRuleMatcher" = proto.Field( + proto.MESSAGE, + number=103668165, + optional=True, + message="NetworkPolicyTrafficClassificationRuleMatcher", + ) + priority: int = proto.Field( + proto.INT32, + number=445151652, + optional=True, + ) + rule_name: str = proto.Field( + proto.STRING, + number=55286254, + optional=True, + ) + rule_tuple_count: int = proto.Field( + proto.INT32, + number=388342037, + optional=True, + ) + target_secure_tags: MutableSequence[ + "NetworkPolicyTrafficClassificationRuleSecureTag" + ] = proto.RepeatedField( + proto.MESSAGE, + number=468132403, + message="NetworkPolicyTrafficClassificationRuleSecureTag", + ) + target_service_accounts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=457639710, + ) + + +class NetworkPolicyTrafficClassificationRuleAction(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + dscp_mode (str): + The traffic class that should be applied to + the matching packet. Check the DscpMode enum for + the list of possible values. + + This field is a member of `oneof`_ ``_dscp_mode``. + dscp_value (int): + Custom DSCP value from 0-63 range. + + This field is a member of `oneof`_ ``_dscp_value``. + traffic_class (str): + The traffic class that should be applied to + the matching packet. Check the TrafficClass enum + for the list of possible values. + + This field is a member of `oneof`_ ``_traffic_class``. + type_ (str): + Always "apply_traffic_classification" for traffic + classification rules. + + This field is a member of `oneof`_ ``_type``. + """ + + class DscpMode(proto.Enum): + r"""The traffic class that should be applied to the matching + packet. + + Values: + UNDEFINED_DSCP_MODE (0): + A value indicating that the enum field is not + set. + AUTO (2020783): + DSCP value will be automatically picked up based on + configured traffic_class. + CUSTOM (388595569): + Allows to specify custom DSCP value from selected + traffic_class range. + """ + UNDEFINED_DSCP_MODE = 0 + AUTO = 2020783 + CUSTOM = 388595569 + + class TrafficClass(proto.Enum): + r"""The traffic class that should be applied to the matching + packet. + + Values: + UNDEFINED_TRAFFIC_CLASS (0): + A value indicating that the enum field is not + set. + TC1 (82850): + Traffic Class 1, corresponding to DSCP ranges + (0-7) 000xxx. + TC2 (82851): + Traffic Class 2, corresponding to DSCP ranges + (8-15) 001xxx. + TC3 (82852): + Traffic Class 3, corresponding to DSCP ranges + (16-23) 010xxx. + TC4 (82853): + Traffic Class 4, corresponding to DSCP ranges + (24-31) 011xxx. + TC5 (82854): + Traffic Class 5, corresponding to DSCP ranges + (32-47) 10xxxx. + TC6 (82855): + Traffic Class 6, corresponding to DSCP ranges + (48-63) 11xxxx. + """ + UNDEFINED_TRAFFIC_CLASS = 0 + TC1 = 82850 + TC2 = 82851 + TC3 = 82852 + TC4 = 82853 + TC5 = 82854 + TC6 = 82855 + + dscp_mode: str = proto.Field( + proto.STRING, + number=242755270, + optional=True, + ) + dscp_value: int = proto.Field( + proto.INT32, + number=17123502, + optional=True, + ) + traffic_class: str = proto.Field( + proto.STRING, + number=198180022, + optional=True, + ) + type_: str = proto.Field( + proto.STRING, + number=3575610, + optional=True, + ) + + +class NetworkPolicyTrafficClassificationRuleMatcher(proto.Message): + r"""Represents a match condition that incoming traffic is + evaluated against. Exactly one field must be specified. + + Attributes: + dest_ip_ranges (MutableSequence[str]): + CIDR IP address range. Maximum number of + destination CIDR IP ranges allowed is 5000. + layer4_configs (MutableSequence[google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRuleMatcherLayer4Config]): + Pairs of IP protocols and ports that the rule + should match. + src_ip_ranges (MutableSequence[str]): + CIDR IP address range. Maximum number of + source CIDR IP ranges allowed is 5000. + """ + + dest_ip_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=337357713, + ) + layer4_configs: MutableSequence[ + "NetworkPolicyTrafficClassificationRuleMatcherLayer4Config" + ] = proto.RepeatedField( + proto.MESSAGE, + number=373534261, + message="NetworkPolicyTrafficClassificationRuleMatcherLayer4Config", + ) + src_ip_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=432128083, + ) + + +class NetworkPolicyTrafficClassificationRuleMatcherLayer4Config(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ip_protocol (str): + The IP protocol to which this rule applies. + The protocol type is required when creating a + traffic classification rule. This value can + either be one of the following well known + protocol strings (tcp, udp, icmp, esp, ah, ipip, + sctp), or the IP protocol number. + + This field is a member of `oneof`_ ``_ip_protocol``. + ports (MutableSequence[str]): + An optional list of ports to which this rule applies. This + field is only applicable for UDP or TCP protocol. Each entry + must be either an integer or a range. If not specified, this + rule applies to connections through any port. Example inputs + include: ["22"], ["80","443"], and ["12345-12349"]. + """ + + ip_protocol: str = proto.Field( + proto.STRING, + number=475958960, + optional=True, + ) + ports: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=106854418, + ) + + +class NetworkPolicyTrafficClassificationRuleSecureTag(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name of the secure tag, created with + TagManager's TagValue API. + + This field is a member of `oneof`_ ``_name``. + state (str): + [Output Only] State of the secure tag, either ``EFFECTIVE`` + or ``INEFFECTIVE``. A secure tag is ``INEFFECTIVE`` when it + is deleted or its network is deleted. 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] State of the secure tag, either ``EFFECTIVE`` or + ``INEFFECTIVE``. A secure tag is ``INEFFECTIVE`` when it is deleted + or its network is deleted. + + Values: + UNDEFINED_STATE (0): + A value indicating that the enum field is not + set. + EFFECTIVE (244201863): + No description available. + INEFFECTIVE (304458242): + No description available. + STATE_UNSPECIFIED (470755401): + No description available. + """ + UNDEFINED_STATE = 0 + EFFECTIVE = 244201863 + INEFFECTIVE = 304458242 + STATE_UNSPECIFIED = 470755401 + + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + state: str = proto.Field( + proto.STRING, + number=109757585, + optional=True, + ) + + class NetworkProfile(proto.Message): r"""NetworkProfile represents a Google managed network profile resource. @@ -94134,14 +96330,76 @@ class PatchRegionHealthCheckRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - health_check: str = proto.Field( + health_check: str = proto.Field( + proto.STRING, + number=308876645, + ) + health_check_resource: "HealthCheck" = proto.Field( + proto.MESSAGE, + number=201925032, + message="HealthCheck", + ) + 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, + ) + + +class PatchRegionHealthCheckServiceRequest(proto.Message): + r"""A request message for RegionHealthCheckServices.Patch. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + health_check_service (str): + Name of the HealthCheckService to update. The + name must be 1-63 characters long, and comply + with RFC1035. + health_check_service_resource (google.cloud.compute_v1beta.types.HealthCheckService): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region scoping 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``. + """ + + health_check_service: str = proto.Field( proto.STRING, - number=308876645, + number=408374747, ) - health_check_resource: "HealthCheck" = proto.Field( + health_check_service_resource: "HealthCheckService" = proto.Field( proto.MESSAGE, - number=201925032, - message="HealthCheck", + number=477367794, + message="HealthCheckService", ) project: str = proto.Field( proto.STRING, @@ -94158,19 +96416,19 @@ class PatchRegionHealthCheckRequest(proto.Message): ) -class PatchRegionHealthCheckServiceRequest(proto.Message): - r"""A request message for RegionHealthCheckServices.Patch. See - the method description for details. +class PatchRegionHealthSourceRequest(proto.Message): + r"""A request message for RegionHealthSources.Patch. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - health_check_service (str): - Name of the HealthCheckService to update. The - name must be 1-63 characters long, and comply - with RFC1035. - health_check_service_resource (google.cloud.compute_v1beta.types.HealthCheckService): + health_source (str): + Name of the HealthSource to update. The name + must be 1-63 characters long, and comply with + RFC1035. + health_source_resource (google.cloud.compute_v1beta.types.HealthSource): The body resource for this request project (str): Project ID for this request. @@ -94196,14 +96454,14 @@ class PatchRegionHealthCheckServiceRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - health_check_service: str = proto.Field( + health_source: str = proto.Field( proto.STRING, - number=408374747, + number=376521566, ) - health_check_service_resource: "HealthCheckService" = proto.Field( + health_source_resource: "HealthSource" = proto.Field( proto.MESSAGE, - number=477367794, - message="HealthCheckService", + number=357735375, + message="HealthSource", ) project: str = proto.Field( proto.STRING, @@ -94340,6 +96598,67 @@ class PatchRegionNetworkFirewallPolicyRequest(proto.Message): ) +class PatchRegionNetworkPolicyRequest(proto.Message): + r"""A request message for RegionNetworkPolicies.Patch. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_policy (str): + Name of the network policy resource to + update. + network_policy_resource (google.cloud.compute_v1beta.types.NetworkPolicy): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region of 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_policy: str = proto.Field( + proto.STRING, + number=504961123, + ) + network_policy_resource: "NetworkPolicy" = proto.Field( + proto.MESSAGE, + number=437886058, + message="NetworkPolicy", + ) + 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, + ) + + class PatchRegionSecurityPolicyRequest(proto.Message): r"""A request message for RegionSecurityPolicies.Patch. See the method description for details. @@ -95430,11 +97749,199 @@ class PatchSslPolicyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - ssl_policy (str): - Name of the SSL policy to update. The name - must be 1-63 characters long, and comply with - RFC1035. - ssl_policy_resource (google.cloud.compute_v1beta.types.SslPolicy): + ssl_policy (str): + Name of the SSL policy to update. The name + must be 1-63 characters long, and comply with + RFC1035. + ssl_policy_resource (google.cloud.compute_v1beta.types.SslPolicy): + 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, + ) + ssl_policy: str = proto.Field( + proto.STRING, + number=295190213, + ) + ssl_policy_resource: "SslPolicy" = proto.Field( + proto.MESSAGE, + number=274891848, + message="SslPolicy", + ) + + +class PatchSubnetworkRequest(proto.Message): + r"""A request message for Subnetworks.Patch. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + drain_timeout_seconds (int): + The drain timeout specifies the upper bound in seconds on + the amount of time allowed to drain connections from the + current ACTIVE subnetwork to the current BACKUP subnetwork. + The drain timeout is only applicable when the following + conditions are true: - the subnetwork being patched has + purpose = INTERNAL_HTTPS_LOAD_BALANCER - the subnetwork + being patched has role = BACKUP - the patch request is + setting the role to ACTIVE. Note that after this patch + operation the roles of the ACTIVE and BACKUP subnetworks + will be swapped. + + This field is a member of `oneof`_ ``_drain_timeout_seconds``. + project (str): + Project ID for this request. + region (str): + Name of the region scoping 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``. + subnetwork (str): + Name of the Subnetwork resource to patch. + subnetwork_resource (google.cloud.compute_v1beta.types.Subnetwork): + The body resource for this request + """ + + drain_timeout_seconds: int = proto.Field( + proto.INT32, + number=357707098, + 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, + ) + subnetwork: str = proto.Field( + proto.STRING, + number=307827694, + ) + subnetwork_resource: "Subnetwork" = proto.Field( + proto.MESSAGE, + number=42233151, + message="Subnetwork", + ) + + +class PatchTargetGrpcProxyRequest(proto.Message): + r"""A request message for TargetGrpcProxies.Patch. 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``. + target_grpc_proxy (str): + Name of the TargetGrpcProxy resource to + patch. + target_grpc_proxy_resource (google.cloud.compute_v1beta.types.TargetGrpcProxy): + 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, + ) + target_grpc_proxy: str = proto.Field( + proto.STRING, + number=5020283, + ) + target_grpc_proxy_resource: "TargetGrpcProxy" = proto.Field( + proto.MESSAGE, + number=328922450, + message="TargetGrpcProxy", + ) + + +class PatchTargetHttpProxyRequest(proto.Message): + r"""A request message for TargetHttpProxies.Patch. 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``. + target_http_proxy (str): + Name of the TargetHttpProxy resource to + patch. + target_http_proxy_resource (google.cloud.compute_v1beta.types.TargetHttpProxy): The body resource for this request """ @@ -95447,42 +97954,27 @@ class PatchSslPolicyRequest(proto.Message): number=37109963, optional=True, ) - ssl_policy: str = proto.Field( + target_http_proxy: str = proto.Field( proto.STRING, - number=295190213, + number=206872421, ) - ssl_policy_resource: "SslPolicy" = proto.Field( + target_http_proxy_resource: "TargetHttpProxy" = proto.Field( proto.MESSAGE, - number=274891848, - message="SslPolicy", + number=24696744, + message="TargetHttpProxy", ) -class PatchSubnetworkRequest(proto.Message): - r"""A request message for Subnetworks.Patch. See the method - description for details. +class PatchTargetHttpsProxyRequest(proto.Message): + r"""A request message for TargetHttpsProxies.Patch. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - drain_timeout_seconds (int): - The drain timeout specifies the upper bound in seconds on - the amount of time allowed to drain connections from the - current ACTIVE subnetwork to the current BACKUP subnetwork. - The drain timeout is only applicable when the following - conditions are true: - the subnetwork being patched has - purpose = INTERNAL_HTTPS_LOAD_BALANCER - the subnetwork - being patched has role = BACKUP - the patch request is - setting the role to ACTIVE. Note that after this patch - operation the roles of the ACTIVE and BACKUP subnetworks - will be swapped. - - This field is a member of `oneof`_ ``_drain_timeout_seconds``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -95501,106 +97993,58 @@ class PatchSubnetworkRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - subnetwork (str): - Name of the Subnetwork resource to patch. - subnetwork_resource (google.cloud.compute_v1beta.types.Subnetwork): + target_https_proxy (str): + Name of the TargetHttpsProxy resource to + patch. + target_https_proxy_resource (google.cloud.compute_v1beta.types.TargetHttpsProxy): The body resource for this request """ - drain_timeout_seconds: int = proto.Field( - proto.INT32, - number=357707098, - 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, ) - subnetwork: str = proto.Field( + target_https_proxy: str = proto.Field( proto.STRING, - number=307827694, + number=52336748, ) - subnetwork_resource: "Subnetwork" = proto.Field( + target_https_proxy_resource: "TargetHttpsProxy" = proto.Field( proto.MESSAGE, - number=42233151, - message="Subnetwork", + number=433657473, + message="TargetHttpsProxy", ) -class PatchTargetGrpcProxyRequest(proto.Message): - r"""A request message for TargetGrpcProxies.Patch. See the method - description for details. +class PatchTrafficClassificationRuleRegionNetworkPolicyRequest(proto.Message): + r"""A request message for + RegionNetworkPolicies.PatchTrafficClassificationRule. 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``. - target_grpc_proxy (str): - Name of the TargetGrpcProxy resource to - patch. - target_grpc_proxy_resource (google.cloud.compute_v1beta.types.TargetGrpcProxy): + network_policy (str): + Name of the network policy resource to + update. + network_policy_traffic_classification_rule_resource (google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule): 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, - ) - target_grpc_proxy: str = proto.Field( - proto.STRING, - number=5020283, - ) - target_grpc_proxy_resource: "TargetGrpcProxy" = proto.Field( - proto.MESSAGE, - number=328922450, - message="TargetGrpcProxy", - ) - - -class PatchTargetHttpProxyRequest(proto.Message): - r"""A request message for TargetHttpProxies.Patch. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + priority (int): + The priority of the traffic classification + rule to patch. Only rules with a priority value + between 1 and 2147482647 (inclusive) can be + patched. - Attributes: + This field is a member of `oneof`_ ``_priority``. project (str): Project ID for this request. + region (str): + Name of the region of this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -95619,86 +98063,35 @@ class PatchTargetHttpProxyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - target_http_proxy (str): - Name of the TargetHttpProxy resource to - patch. - target_http_proxy_resource (google.cloud.compute_v1beta.types.TargetHttpProxy): - The body resource for this request """ - project: str = proto.Field( + network_policy: str = proto.Field( proto.STRING, - number=227560217, + number=504961123, ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - target_http_proxy: str = proto.Field( - proto.STRING, - number=206872421, - ) - target_http_proxy_resource: "TargetHttpProxy" = proto.Field( + network_policy_traffic_classification_rule_resource: "NetworkPolicyTrafficClassificationRule" = proto.Field( proto.MESSAGE, - number=24696744, - message="TargetHttpProxy", + number=464294582, + message="NetworkPolicyTrafficClassificationRule", + ) + priority: int = proto.Field( + proto.INT32, + number=445151652, + optional=True, ) - - -class PatchTargetHttpsProxyRequest(proto.Message): - r"""A request message for TargetHttpsProxies.Patch. 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``. - target_https_proxy (str): - Name of the TargetHttpsProxy resource to - patch. - target_https_proxy_resource (google.cloud.compute_v1beta.types.TargetHttpsProxy): - The body resource for this request - """ - 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, ) - target_https_proxy: str = proto.Field( - proto.STRING, - number=52336748, - ) - target_https_proxy_resource: "TargetHttpsProxy" = proto.Field( - proto.MESSAGE, - number=433657473, - message="TargetHttpsProxy", - ) class PatchUrlMapRequest(proto.Message): @@ -98282,6 +100675,11 @@ class PublicDelegatedPrefix(proto.Message): resource. This field is a member of `oneof`_ ``_description``. + enable_enhanced_ipv4_allocation (bool): + [Output Only] Whether this PDP supports enhanced IPv4 + allocations. Applicable for IPv4 PDPs only. + + This field is a member of `oneof`_ ``_enable_enhanced_ipv4_allocation``. fingerprint (str): Fingerprint of this resource. A hash of the contents stored in this object. This field is @@ -98471,6 +100869,11 @@ class Status(proto.Enum): number=422937596, optional=True, ) + enable_enhanced_ipv4_allocation: bool = proto.Field( + proto.BOOL, + number=54582253, + optional=True, + ) fingerprint: str = proto.Field( proto.STRING, number=234678500, @@ -98715,6 +101118,11 @@ class PublicDelegatedPrefixPublicDelegatedSubPrefix(proto.Message): resource. This field is a member of `oneof`_ ``_description``. + enable_enhanced_ipv4_allocation (bool): + [Output Only] Whether this PDP supports enhanced IPv4 + allocations. Applicable for IPv4 PDPs only. + + This field is a member of `oneof`_ ``_enable_enhanced_ipv4_allocation``. ip_cidr_range (str): The IP address range, in CIDR format, represented by this sub public delegated prefix. @@ -98803,6 +101211,11 @@ class Status(proto.Enum): number=422937596, optional=True, ) + enable_enhanced_ipv4_allocation: bool = proto.Field( + proto.BOOL, + number=54582253, + optional=True, + ) ip_cidr_range: str = proto.Field( proto.STRING, number=98117322, @@ -101883,6 +104296,71 @@ class RemoveAssociationRegionNetworkFirewallPolicyRequest(proto.Message): ) +class RemoveAssociationRegionNetworkPolicyRequest(proto.Message): + r"""A request message for + RegionNetworkPolicies.RemoveAssociation. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name for the association that will be + removed. + + This field is a member of `oneof`_ ``_name``. + network_policy (str): + Name of the network policy resource to + update. + project (str): + Project ID for this request. + region (str): + Name of the region of 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``. + """ + + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + network_policy: str = proto.Field( + proto.STRING, + number=504961123, + ) + 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, + ) + + class RemoveHealthCheckTargetPoolRequest(proto.Message): r"""A request message for TargetPools.RemoveHealthCheck. See the method description for details. @@ -102712,6 +105190,141 @@ class RemoveRuleSecurityPolicyRequest(proto.Message): ) +class RemoveTrafficClassificationRuleRegionNetworkPolicyRequest(proto.Message): + r"""A request message for + RegionNetworkPolicies.RemoveTrafficClassificationRule. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_policy (str): + Name of the network policy resource to + update. + priority (int): + The priority of the rule to remove from the + network policy. + + This field is a member of `oneof`_ ``_priority``. + project (str): + Project ID for this request. + region (str): + Name of the region of 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_policy: str = proto.Field( + proto.STRING, + number=504961123, + ) + priority: int = proto.Field( + proto.INT32, + number=445151652, + 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, + ) + + +class ReportFaultyReservationSubBlockRequest(proto.Message): + r"""A request message for ReservationSubBlocks.ReportFaulty. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent_name (str): + The name of the parent reservation and parent block. In the + format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + 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``. + reservation_sub_block (str): + The name of the reservation subBlock. Name + should conform to RFC1035 or be a resource ID. + reservation_sub_blocks_report_faulty_request_resource (google.cloud.compute_v1beta.types.ReservationSubBlocksReportFaultyRequest): + The body resource for this request + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. + """ + + parent_name: str = proto.Field( + proto.STRING, + number=478151936, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + reservation_sub_block: str = proto.Field( + proto.STRING, + number=22750491, + ) + reservation_sub_blocks_report_faulty_request_resource: "ReservationSubBlocksReportFaultyRequest" = proto.Field( + proto.MESSAGE, + number=450847938, + message="ReservationSubBlocksReportFaultyRequest", + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class ReportHostAsFaultyInstanceRequest(proto.Message): r"""A request message for Instances.ReportHostAsFaulty. See the method description for details. @@ -104450,6 +107063,136 @@ def raw_page(self): ) +class ReservationSubBlocksReportFaultyRequest(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disruption_schedule (str): + The disruption schedule for the subBlock. + Check the DisruptionSchedule enum for the list + of possible values. + + This field is a member of `oneof`_ ``_disruption_schedule``. + failure_component (str): + The component that experienced the fault. + Check the FailureComponent enum for the list of + possible values. + + This field is a member of `oneof`_ ``_failure_component``. + fault_reasons (MutableSequence[google.cloud.compute_v1beta.types.ReservationSubBlocksReportFaultyRequestFaultReason]): + The reasons for the fault experienced with + the subBlock. + """ + + class DisruptionSchedule(proto.Enum): + r"""The disruption schedule for the subBlock. + + Values: + UNDEFINED_DISRUPTION_SCHEDULE (0): + A value indicating that the enum field is not + set. + DISRUPTION_SCHEDULE_UNSPECIFIED (332543835): + No description available. + IMMEDIATE (152881041): + All VMs will be disrupted immediately. + """ + UNDEFINED_DISRUPTION_SCHEDULE = 0 + DISRUPTION_SCHEDULE_UNSPECIFIED = 332543835 + IMMEDIATE = 152881041 + + class FailureComponent(proto.Enum): + r"""The component that experienced the fault. + + Values: + UNDEFINED_FAILURE_COMPONENT (0): + A value indicating that the enum field is not + set. + FAILURE_COMPONENT_UNSPECIFIED (332003744): + No description available. + MULTIPLE_FAULTY_HOSTS (423545298): + Multiple hosts experienced the fault. + NVLINK_SWITCH (239107153): + The NVLink switch experienced the fault. + """ + UNDEFINED_FAILURE_COMPONENT = 0 + FAILURE_COMPONENT_UNSPECIFIED = 332003744 + MULTIPLE_FAULTY_HOSTS = 423545298 + NVLINK_SWITCH = 239107153 + + disruption_schedule: str = proto.Field( + proto.STRING, + number=95871619, + optional=True, + ) + failure_component: str = proto.Field( + proto.STRING, + number=25912456, + optional=True, + ) + fault_reasons: MutableSequence[ + "ReservationSubBlocksReportFaultyRequestFaultReason" + ] = proto.RepeatedField( + proto.MESSAGE, + number=168056210, + message="ReservationSubBlocksReportFaultyRequestFaultReason", + ) + + +class ReservationSubBlocksReportFaultyRequestFaultReason(proto.Message): + r"""The reason for the fault experienced with the subBlock. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + behavior (str): + The behavior of the fault experienced with + the subBlock. Check the Behavior enum for the + list of possible values. + + This field is a member of `oneof`_ ``_behavior``. + description (str): + The description of the fault experienced with + the subBlock. + + This field is a member of `oneof`_ ``_description``. + """ + + class Behavior(proto.Enum): + r"""The behavior of the fault experienced with the subBlock. + + Values: + UNDEFINED_BEHAVIOR (0): + A value indicating that the enum field is not + set. + FAULT_BEHAVIOR_UNSPECIFIED (447660743): + No description available. + GPU_ERROR (198817909): + The subBlock experienced a GPU error. + PERFORMANCE (135701520): + The subBlock experienced performance issues. + SWITCH_FAILURE (254909279): + The subBlock experienced a switch failure. + """ + UNDEFINED_BEHAVIOR = 0 + FAULT_BEHAVIOR_UNSPECIFIED = 447660743 + GPU_ERROR = 198817909 + PERFORMANCE = 135701520 + SWITCH_FAILURE = 254909279 + + behavior: str = proto.Field( + proto.STRING, + number=437170770, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + + class ReservationsBlocksPerformMaintenanceRequest(proto.Message): r""" @@ -120277,7 +123020,6 @@ class Snapshot(proto.Message): r"""Represents a Persistent Disk Snapshot resource. You can use snapshots to back up data on a regular interval. For more information, read Creating persistent disk snapshots. - LINT.IfChange .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -120400,6 +123142,11 @@ class Snapshot(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + params (google.cloud.compute_v1beta.types.SnapshotParams): + Input only. [Input Only] Additional params passed with the + request, but not persisted as part of resource payload. + + This field is a member of `oneof`_ ``_params``. region (str): [Output Only] URL of the region where the snapshot resides. Only applicable for regional snapshots. @@ -120704,6 +123451,12 @@ class StorageBytesStatus(proto.Enum): number=3373707, optional=True, ) + params: "SnapshotParams" = proto.Field( + proto.MESSAGE, + number=78313862, + optional=True, + message="SnapshotParams", + ) region: str = proto.Field( proto.STRING, number=138946292, @@ -120970,6 +123723,25 @@ def raw_page(self): ) +class SnapshotParams(proto.Message): + r"""Additional snapshot params. + + Attributes: + resource_manager_tags (MutableMapping[str, str]): + Resource manager tags to be bound to the snapshot. 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: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=377671164, + ) + + class SnapshotSettings(proto.Message): r""" @@ -130896,6 +133668,40 @@ class TestIamPermissionsRegionHealthCheckServiceRequest(proto.Message): ) +class TestIamPermissionsRegionHealthSourceRequest(proto.Message): + r"""A request message for RegionHealthSources.TestIamPermissions. + See the method description for details. + + Attributes: + 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. + test_permissions_request_resource (google.cloud.compute_v1beta.types.TestPermissionsRequest): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + test_permissions_request_resource: "TestPermissionsRequest" = proto.Field( + proto.MESSAGE, + number=439214758, + message="TestPermissionsRequest", + ) + + class TestIamPermissionsRegionInstanceGroupManagerRequest(proto.Message): r"""A request message for RegionInstanceGroupManagers.TestIamPermissions. See the method diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_aggregated_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_aggregated_list_sync.py new file mode 100644 index 000000000000..219fba7f4fc2 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_aggregated_list_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionHealthSources_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_v1beta + + +def sample_aggregated_list(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.AggregatedListRegionHealthSourcesRequest( + 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_v1beta_generated_RegionHealthSources_AggregatedList_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_delete_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_delete_sync.py new file mode 100644 index 000000000000..5d5ddd9162f0 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionHealthSources_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_v1beta + + +def sample_delete(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteRegionHealthSourceRequest( + health_source="health_source_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionHealthSources_Delete_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_get_sync.py new file mode 100644 index 000000000000..627aeb5b1c8f --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionHealthSources_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_v1beta + + +def sample_get(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetRegionHealthSourceRequest( + health_source="health_source_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionHealthSources_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_insert_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_insert_sync.py new file mode 100644 index 000000000000..7f6028bcd1ad --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_insert_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionHealthSources_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_v1beta + + +def sample_insert(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertRegionHealthSourceRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionHealthSources_Insert_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_list_sync.py new file mode 100644 index 000000000000..6b3462bbc4cf --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionHealthSources_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_v1beta + + +def sample_list(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.ListRegionHealthSourcesRequest( + project="project_value", + region="region_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END compute_v1beta_generated_RegionHealthSources_List_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_patch_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_patch_sync.py new file mode 100644 index 000000000000..d28c040611c0 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_patch_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Patch +# 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-v1beta + + +# [START compute_v1beta_generated_RegionHealthSources_Patch_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_v1beta + + +def sample_patch(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchRegionHealthSourceRequest( + health_source="health_source_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionHealthSources_Patch_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_test_iam_permissions_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_test_iam_permissions_sync.py new file mode 100644 index 000000000000..ed33f4184a76 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_health_sources_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 TestIamPermissions +# 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-v1beta + + +# [START compute_v1beta_generated_RegionHealthSources_TestIamPermissions_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_v1beta + + +def sample_test_iam_permissions(): + # Create a client + client = compute_v1beta.RegionHealthSourcesClient() + + # Initialize request argument(s) + request = compute_v1beta.TestIamPermissionsRegionHealthSourceRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionHealthSources_TestIamPermissions_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_add_association_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_add_association_sync.py new file mode 100644 index 000000000000..70b7626f649f --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_add_association_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 AddAssociation +# 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_AddAssociation_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_v1beta + + +def sample_add_association(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.AddAssociationRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.add_association(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_AddAssociation_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_add_traffic_classification_rule_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_add_traffic_classification_rule_sync.py new file mode 100644 index 000000000000..0e11e157ebe8 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_add_traffic_classification_rule_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 AddTrafficClassificationRule +# 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_AddTrafficClassificationRule_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_v1beta + + +def sample_add_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.AddTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.add_traffic_classification_rule(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_AddTrafficClassificationRule_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_aggregated_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_aggregated_list_sync.py new file mode 100644 index 000000000000..30be9d14bc9c --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_aggregated_list_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_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_v1beta + + +def sample_aggregated_list(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.AggregatedListRegionNetworkPoliciesRequest( + 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_v1beta_generated_RegionNetworkPolicies_AggregatedList_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_delete_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_delete_sync.py new file mode 100644 index 000000000000..226de8b0d3a2 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_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_v1beta + + +def sample_delete(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_Delete_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_association_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_association_sync.py new file mode 100644 index 000000000000..9095e633a2cc --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_association_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 GetAssociation +# 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_GetAssociation_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_v1beta + + +def sample_get_association(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetAssociationRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get_association(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_GetAssociation_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_sync.py new file mode 100644 index 000000000000..463eeb1b3b40 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_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_v1beta + + +def sample_get(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_traffic_classification_rule_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_traffic_classification_rule_sync.py new file mode 100644 index 000000000000..7c1ce0246008 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_get_traffic_classification_rule_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 GetTrafficClassificationRule +# 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_GetTrafficClassificationRule_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_v1beta + + +def sample_get_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.GetTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get_traffic_classification_rule(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_GetTrafficClassificationRule_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_insert_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_insert_sync.py new file mode 100644 index 000000000000..3ec848c95ca5 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_insert_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_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_v1beta + + +def sample_insert(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertRegionNetworkPolicyRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_Insert_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_list_sync.py new file mode 100644 index 000000000000..f24b117e0346 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_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_v1beta + + +def sample_list(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.ListRegionNetworkPoliciesRequest( + project="project_value", + region="region_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_List_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_patch_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_patch_sync.py new file mode 100644 index 000000000000..abf113f4f62a --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_patch_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Patch +# 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_Patch_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_v1beta + + +def sample_patch(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_Patch_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_patch_traffic_classification_rule_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_patch_traffic_classification_rule_sync.py new file mode 100644 index 000000000000..2db4c12ab2d5 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_patch_traffic_classification_rule_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 PatchTrafficClassificationRule +# 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_PatchTrafficClassificationRule_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_v1beta + + +def sample_patch_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.PatchTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.patch_traffic_classification_rule(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_PatchTrafficClassificationRule_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_remove_association_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_remove_association_sync.py new file mode 100644 index 000000000000..dee3e08fa459 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_remove_association_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 RemoveAssociation +# 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_RemoveAssociation_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_v1beta + + +def sample_remove_association(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.RemoveAssociationRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.remove_association(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_RemoveAssociation_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_remove_traffic_classification_rule_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_remove_traffic_classification_rule_sync.py new file mode 100644 index 000000000000..c24fd6e3ebb0 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_network_policies_remove_traffic_classification_rule_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 RemoveTrafficClassificationRule +# 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-v1beta + + +# [START compute_v1beta_generated_RegionNetworkPolicies_RemoveTrafficClassificationRule_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_v1beta + + +def sample_remove_traffic_classification_rule(): + # Create a client + client = compute_v1beta.RegionNetworkPoliciesClient() + + # Initialize request argument(s) + request = compute_v1beta.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest( + network_policy="network_policy_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.remove_traffic_classification_rule(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_RegionNetworkPolicies_RemoveTrafficClassificationRule_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_report_faulty_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_report_faulty_sync.py new file mode 100644 index 000000000000..8f180ecfb7ed --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_report_faulty_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 ReportFaulty +# 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-v1beta + + +# [START compute_v1beta_generated_ReservationSubBlocks_ReportFaulty_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_v1beta + + +def sample_report_faulty(): + # Create a client + client = compute_v1beta.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1beta.ReportFaultyReservationSubBlockRequest( + parent_name="parent_name_value", + project="project_value", + reservation_sub_block="reservation_sub_block_value", + zone="zone_value", + ) + + # Make the request + response = client.report_faulty(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_ReservationSubBlocks_ReportFaulty_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json b/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json index 9d00e8628914..12727156888e 100644 --- a/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json @@ -48967,39 +48967,27 @@ "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", - "shortName": "RegionInstanceGroupManagerResizeRequestsClient" + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient", + "shortName": "RegionHealthSourcesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.cancel", + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.Cancel", + "fullName": "google.cloud.compute.v1beta.RegionHealthSources.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", - "shortName": "RegionInstanceGroupManagerResizeRequests" + "fullName": "google.cloud.compute.v1beta.RegionHealthSources", + "shortName": "RegionHealthSources" }, - "shortName": "Cancel" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.CancelRegionInstanceGroupManagerResizeRequestRequest" + "type": "google.cloud.compute_v1beta.types.AggregatedListRegionHealthSourcesRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, - { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "resize_request", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -49013,22 +49001,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "cancel" + "resultType": "google.cloud.compute_v1beta.services.region_health_sources.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Cancel", - "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_cancel_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1beta_generated_region_health_sources_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_Cancel_sync", + "regionTag": "compute_v1beta_generated_RegionHealthSources_AggregatedList_sync", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -49038,43 +49026,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_cancel_sync.py" + "title": "compute_v1beta_generated_region_health_sources_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", - "shortName": "RegionInstanceGroupManagerResizeRequestsClient" + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient", + "shortName": "RegionHealthSourcesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.delete", + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.Delete", + "fullName": "google.cloud.compute.v1beta.RegionHealthSources.Delete", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", - "shortName": "RegionInstanceGroupManagerResizeRequests" + "fullName": "google.cloud.compute.v1beta.RegionHealthSources", + "shortName": "RegionHealthSources" }, "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteRegionInstanceGroupManagerResizeRequestRequest" + "type": "google.cloud.compute_v1beta.types.DeleteRegionHealthSourceRequest" }, { "name": "project", @@ -49085,11 +49073,7 @@ "type": "str" }, { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "resize_request", + "name": "health_source", "type": "str" }, { @@ -49109,18 +49093,18 @@ "shortName": "delete" }, "description": "Sample for Delete", - "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_delete_sync.py", + "file": "compute_v1beta_generated_region_health_sources_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_Delete_sync", + "regionTag": "compute_v1beta_generated_RegionHealthSources_Delete_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -49130,43 +49114,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_delete_sync.py" + "title": "compute_v1beta_generated_region_health_sources_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", - "shortName": "RegionInstanceGroupManagerResizeRequestsClient" + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient", + "shortName": "RegionHealthSourcesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.get", + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.Get", + "fullName": "google.cloud.compute.v1beta.RegionHealthSources.Get", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", - "shortName": "RegionInstanceGroupManagerResizeRequests" + "fullName": "google.cloud.compute.v1beta.RegionHealthSources", + "shortName": "RegionHealthSources" }, "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionInstanceGroupManagerResizeRequestRequest" + "type": "google.cloud.compute_v1beta.types.GetRegionHealthSourceRequest" }, { "name": "project", @@ -49177,11 +49161,7 @@ "type": "str" }, { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "resize_request", + "name": "health_source", "type": "str" }, { @@ -49197,22 +49177,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.InstanceGroupManagerResizeRequest", + "resultType": "google.cloud.compute_v1beta.types.HealthSource", "shortName": "get" }, "description": "Sample for Get", - "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_get_sync.py", + "file": "compute_v1beta_generated_region_health_sources_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_Get_sync", + "regionTag": "compute_v1beta_generated_RegionHealthSources_Get_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -49222,43 +49202,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_get_sync.py" + "title": "compute_v1beta_generated_region_health_sources_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", - "shortName": "RegionInstanceGroupManagerResizeRequestsClient" + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient", + "shortName": "RegionHealthSourcesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.insert", + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient.insert", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.Insert", + "fullName": "google.cloud.compute.v1beta.RegionHealthSources.Insert", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", - "shortName": "RegionInstanceGroupManagerResizeRequests" + "fullName": "google.cloud.compute.v1beta.RegionHealthSources", + "shortName": "RegionHealthSources" }, "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertRegionInstanceGroupManagerResizeRequestRequest" + "type": "google.cloud.compute_v1beta.types.InsertRegionHealthSourceRequest" }, { "name": "project", @@ -49269,12 +49249,8 @@ "type": "str" }, { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "instance_group_manager_resize_request_resource", - "type": "google.cloud.compute_v1beta.types.InstanceGroupManagerResizeRequest" + "name": "health_source_resource", + "type": "google.cloud.compute_v1beta.types.HealthSource" }, { "name": "retry", @@ -49293,18 +49269,18 @@ "shortName": "insert" }, "description": "Sample for Insert", - "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_insert_sync.py", + "file": "compute_v1beta_generated_region_health_sources_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_Insert_sync", + "regionTag": "compute_v1beta_generated_RegionHealthSources_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -49314,43 +49290,43 @@ "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_v1beta_generated_region_instance_group_manager_resize_requests_insert_sync.py" + "title": "compute_v1beta_generated_region_health_sources_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", - "shortName": "RegionInstanceGroupManagerResizeRequestsClient" + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient", + "shortName": "RegionHealthSourcesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.list", + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.List", + "fullName": "google.cloud.compute.v1beta.RegionHealthSources.List", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", - "shortName": "RegionInstanceGroupManagerResizeRequests" + "fullName": "google.cloud.compute.v1beta.RegionHealthSources", + "shortName": "RegionHealthSources" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionInstanceGroupManagerResizeRequestsRequest" + "type": "google.cloud.compute_v1beta.types.ListRegionHealthSourcesRequest" }, { "name": "project", @@ -49360,10 +49336,6 @@ "name": "region", "type": "str" }, - { - "name": "instance_group_manager", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -49377,22 +49349,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instance_group_manager_resize_requests.pagers.ListPager", + "resultType": "google.cloud.compute_v1beta.services.region_health_sources.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_list_sync.py", + "file": "compute_v1beta_generated_region_health_sources_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_List_sync", + "regionTag": "compute_v1beta_generated_RegionHealthSources_List_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -49402,43 +49374,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 51, + "end": 54, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_list_sync.py" + "title": "compute_v1beta_generated_region_health_sources_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient", + "shortName": "RegionHealthSourcesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.abandon_instances", + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient.patch", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.AbandonInstances", + "fullName": "google.cloud.compute.v1beta.RegionHealthSources.Patch", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1beta.RegionHealthSources", + "shortName": "RegionHealthSources" }, - "shortName": "AbandonInstances" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.AbandonInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.PatchRegionHealthSourceRequest" }, { "name": "project", @@ -49449,12 +49421,12 @@ "type": "str" }, { - "name": "instance_group_manager", + "name": "health_source", "type": "str" }, { - "name": "region_instance_group_managers_abandon_instances_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersAbandonInstancesRequest" + "name": "health_source_resource", + "type": "google.cloud.compute_v1beta.types.HealthSource" }, { "name": "retry", @@ -49470,13 +49442,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "abandon_instances" + "shortName": "patch" }, - "description": "Sample for AbandonInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_abandon_instances_sync.py", + "description": "Sample for Patch", + "file": "compute_v1beta_generated_region_health_sources_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_AbandonInstances_sync", + "regionTag": "compute_v1beta_generated_RegionHealthSources_Patch_sync", "segments": [ { "end": 53, @@ -49509,28 +49481,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_abandon_instances_sync.py" + "title": "compute_v1beta_generated_region_health_sources_patch_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient", + "shortName": "RegionHealthSourcesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.apply_updates_to_instances", + "fullName": "google.cloud.compute_v1beta.RegionHealthSourcesClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ApplyUpdatesToInstances", + "fullName": "google.cloud.compute.v1beta.RegionHealthSources.TestIamPermissions", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1beta.RegionHealthSources", + "shortName": "RegionHealthSources" }, - "shortName": "ApplyUpdatesToInstances" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionHealthSourceRequest" }, { "name": "project", @@ -49541,12 +49513,12 @@ "type": "str" }, { - "name": "instance_group_manager", + "name": "resource", "type": "str" }, { - "name": "region_instance_group_managers_apply_updates_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersApplyUpdatesRequest" + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1beta.types.TestPermissionsRequest" }, { "name": "retry", @@ -49561,14 +49533,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "apply_updates_to_instances" + "resultType": "google.cloud.compute_v1beta.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for ApplyUpdatesToInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_apply_updates_to_instances_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1beta_generated_region_health_sources_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ApplyUpdatesToInstances_sync", + "regionTag": "compute_v1beta_generated_RegionHealthSources_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -49601,28 +49573,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_apply_updates_to_instances_sync.py" + "title": "compute_v1beta_generated_region_health_sources_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", + "shortName": "RegionInstanceGroupManagerResizeRequestsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.create_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.cancel", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.CreateInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.Cancel", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", + "shortName": "RegionInstanceGroupManagerResizeRequests" }, - "shortName": "CreateInstances" + "shortName": "Cancel" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.CreateInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.CancelRegionInstanceGroupManagerResizeRequestRequest" }, { "name": "project", @@ -49637,8 +49609,8 @@ "type": "str" }, { - "name": "region_instance_group_managers_create_instances_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersCreateInstancesRequest" + "name": "resize_request", + "type": "str" }, { "name": "retry", @@ -49654,21 +49626,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "create_instances" + "shortName": "cancel" }, - "description": "Sample for CreateInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_create_instances_sync.py", + "description": "Sample for Cancel", + "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_cancel_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_CreateInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_Cancel_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -49678,43 +49650,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_create_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_cancel_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", + "shortName": "RegionInstanceGroupManagerResizeRequestsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.delete_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.DeleteInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.Delete", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", + "shortName": "RegionInstanceGroupManagerResizeRequests" }, - "shortName": "DeleteInstances" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.DeleteRegionInstanceGroupManagerResizeRequestRequest" }, { "name": "project", @@ -49729,8 +49701,8 @@ "type": "str" }, { - "name": "region_instance_group_managers_delete_instances_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersDeleteInstancesRequest" + "name": "resize_request", + "type": "str" }, { "name": "retry", @@ -49746,21 +49718,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete_instances" + "shortName": "delete" }, - "description": "Sample for DeleteInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_delete_instances_sync.py", + "description": "Sample for Delete", + "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_DeleteInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_Delete_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -49770,43 +49742,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_delete_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", + "shortName": "RegionInstanceGroupManagerResizeRequestsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.delete_per_instance_configs", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.DeletePerInstanceConfigs", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.Get", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", + "shortName": "RegionInstanceGroupManagerResizeRequests" }, - "shortName": "DeletePerInstanceConfigs" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeletePerInstanceConfigsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.GetRegionInstanceGroupManagerResizeRequestRequest" }, { "name": "project", @@ -49821,8 +49793,8 @@ "type": "str" }, { - "name": "region_instance_group_manager_delete_instance_config_req_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagerDeleteInstanceConfigReq" + "name": "resize_request", + "type": "str" }, { "name": "retry", @@ -49837,22 +49809,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete_per_instance_configs" + "resultType": "google.cloud.compute_v1beta.types.InstanceGroupManagerResizeRequest", + "shortName": "get" }, - "description": "Sample for DeletePerInstanceConfigs", - "file": "compute_v1beta_generated_region_instance_group_managers_delete_per_instance_configs_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_DeletePerInstanceConfigs_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_Get_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -49862,43 +49834,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_delete_per_instance_configs_sync.py" + "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", + "shortName": "RegionInstanceGroupManagerResizeRequestsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.delete", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.insert", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Delete", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.Insert", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", + "shortName": "RegionInstanceGroupManagerResizeRequests" }, - "shortName": "Delete" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.InsertRegionInstanceGroupManagerResizeRequestRequest" }, { "name": "project", @@ -49912,6 +49884,10 @@ "name": "instance_group_manager", "type": "str" }, + { + "name": "instance_group_manager_resize_request_resource", + "type": "google.cloud.compute_v1beta.types.InstanceGroupManagerResizeRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -49926,13 +49902,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "insert" }, - "description": "Sample for Delete", - "file": "compute_v1beta_generated_region_instance_group_managers_delete_sync.py", + "description": "Sample for Insert", + "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Delete_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_Insert_sync", "segments": [ { "end": 53, @@ -49965,28 +49941,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_delete_sync.py" + "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient", + "shortName": "RegionInstanceGroupManagerResizeRequestsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.get", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagerResizeRequestsClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Get", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests.List", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagerResizeRequests", + "shortName": "RegionInstanceGroupManagerResizeRequests" }, - "shortName": "Get" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.ListRegionInstanceGroupManagerResizeRequestsRequest" }, { "name": "project", @@ -50013,22 +49989,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.InstanceGroupManager", - "shortName": "get" + "resultType": "google.cloud.compute_v1beta.services.region_instance_group_manager_resize_requests.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_region_instance_group_managers_get_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_region_instance_group_manager_resize_requests_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Get_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagerResizeRequests_List_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -50048,12 +50024,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 55, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_get_sync.py" + "title": "compute_v1beta_generated_region_instance_group_manager_resize_requests_list_sync.py" }, { "canonical": true, @@ -50062,19 +50038,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.insert", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.abandon_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Insert", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.AbandonInstances", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Insert" + "shortName": "AbandonInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.AbandonInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -50085,8 +50061,12 @@ "type": "str" }, { - "name": "instance_group_manager_resource", - "type": "google.cloud.compute_v1beta.types.InstanceGroupManager" + "name": "instance_group_manager", + "type": "str" + }, + { + "name": "region_instance_group_managers_abandon_instances_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersAbandonInstancesRequest" }, { "name": "retry", @@ -50102,21 +50082,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "abandon_instances" }, - "description": "Sample for Insert", - "file": "compute_v1beta_generated_region_instance_group_managers_insert_sync.py", + "description": "Sample for AbandonInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_abandon_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Insert_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_AbandonInstances_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -50126,22 +50106,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": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_insert_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_abandon_instances_sync.py" }, { "canonical": true, @@ -50150,19 +50130,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.list_errors", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.apply_updates_to_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ListErrors", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ApplyUpdatesToInstances", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ListErrors" + "shortName": "ApplyUpdatesToInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListErrorsRegionInstanceGroupManagersRequest" + "type": "google.cloud.compute_v1beta.types.ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -50176,6 +50156,10 @@ "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_managers_apply_updates_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersApplyUpdatesRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -50189,22 +50173,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instance_group_managers.pagers.ListErrorsPager", - "shortName": "list_errors" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "apply_updates_to_instances" }, - "description": "Sample for ListErrors", - "file": "compute_v1beta_generated_region_instance_group_managers_list_errors_sync.py", + "description": "Sample for ApplyUpdatesToInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_apply_updates_to_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ListErrors_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ApplyUpdatesToInstances_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -50224,12 +50208,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_list_errors_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_apply_updates_to_instances_sync.py" }, { "canonical": true, @@ -50238,19 +50222,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.list_managed_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.create_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ListManagedInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.CreateInstances", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ListManagedInstances" + "shortName": "CreateInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListManagedInstancesRegionInstanceGroupManagersRequest" + "type": "google.cloud.compute_v1beta.types.CreateInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -50264,6 +50248,10 @@ "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_managers_create_instances_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersCreateInstancesRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -50277,22 +50265,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instance_group_managers.pagers.ListManagedInstancesPager", - "shortName": "list_managed_instances" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "create_instances" }, - "description": "Sample for ListManagedInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_list_managed_instances_sync.py", + "description": "Sample for CreateInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_create_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ListManagedInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_CreateInstances_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -50312,12 +50300,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_list_managed_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_create_instances_sync.py" }, { "canonical": true, @@ -50326,19 +50314,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.list_per_instance_configs", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.delete_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ListPerInstanceConfigs", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.DeleteInstances", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ListPerInstanceConfigs" + "shortName": "DeleteInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListPerInstanceConfigsRegionInstanceGroupManagersRequest" + "type": "google.cloud.compute_v1beta.types.DeleteInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -50353,8 +50341,12 @@ "type": "str" }, { - "name": "retry", - "type": "google.api_core.retry.Retry" + "name": "region_instance_group_managers_delete_instances_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersDeleteInstancesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" }, { "name": "timeout", @@ -50365,22 +50357,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instance_group_managers.pagers.ListPerInstanceConfigsPager", - "shortName": "list_per_instance_configs" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete_instances" }, - "description": "Sample for ListPerInstanceConfigs", - "file": "compute_v1beta_generated_region_instance_group_managers_list_per_instance_configs_sync.py", + "description": "Sample for DeleteInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_delete_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ListPerInstanceConfigs_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_DeleteInstances_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -50400,12 +50392,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_list_per_instance_configs_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_delete_instances_sync.py" }, { "canonical": true, @@ -50414,19 +50406,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.list", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.delete_per_instance_configs", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.List", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.DeletePerInstanceConfigs", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "List" + "shortName": "DeletePerInstanceConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionInstanceGroupManagersRequest" + "type": "google.cloud.compute_v1beta.types.DeletePerInstanceConfigsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -50436,6 +50428,14 @@ "name": "region", "type": "str" }, + { + "name": "instance_group_manager", + "type": "str" + }, + { + "name": "region_instance_group_manager_delete_instance_config_req_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagerDeleteInstanceConfigReq" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -50449,14 +50449,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instance_group_managers.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete_per_instance_configs" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_region_instance_group_managers_list_sync.py", + "description": "Sample for DeletePerInstanceConfigs", + "file": "compute_v1beta_generated_region_instance_group_managers_delete_per_instance_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_List_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_DeletePerInstanceConfigs_sync", "segments": [ { "end": 53, @@ -50474,22 +50474,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_v1beta_generated_region_instance_group_managers_list_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_delete_per_instance_configs_sync.py" }, { "canonical": true, @@ -50498,19 +50498,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.patch_per_instance_configs", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.PatchPerInstanceConfigs", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Delete", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "PatchPerInstanceConfigs" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.DeleteRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -50524,10 +50524,6 @@ "name": "instance_group_manager", "type": "str" }, - { - "name": "region_instance_group_manager_patch_instance_config_req_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagerPatchInstanceConfigReq" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -50542,13 +50538,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch_per_instance_configs" + "shortName": "delete" }, - "description": "Sample for PatchPerInstanceConfigs", - "file": "compute_v1beta_generated_region_instance_group_managers_patch_per_instance_configs_sync.py", + "description": "Sample for Delete", + "file": "compute_v1beta_generated_region_instance_group_managers_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_PatchPerInstanceConfigs_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Delete_sync", "segments": [ { "end": 53, @@ -50581,7 +50577,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_patch_per_instance_configs_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_delete_sync.py" }, { "canonical": true, @@ -50590,19 +50586,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.patch", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Patch", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Get", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Patch" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.PatchRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.GetRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -50616,10 +50612,6 @@ "name": "instance_group_manager", "type": "str" }, - { - "name": "instance_group_manager_resource", - "type": "google.cloud.compute_v1beta.types.InstanceGroupManager" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -50633,14 +50625,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1beta.types.InstanceGroupManager", + "shortName": "get" }, - "description": "Sample for Patch", - "file": "compute_v1beta_generated_region_instance_group_managers_patch_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_instance_group_managers_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Patch_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Get_sync", "segments": [ { "end": 53, @@ -50673,7 +50665,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_patch_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_get_sync.py" }, { "canonical": true, @@ -50682,19 +50674,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.recreate_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.insert", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.RecreateInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Insert", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "RecreateInstances" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.RecreateInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.InsertRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -50705,12 +50697,8 @@ "type": "str" }, { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "region_instance_group_managers_recreate_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersRecreateRequest" + "name": "instance_group_manager_resource", + "type": "google.cloud.compute_v1beta.types.InstanceGroupManager" }, { "name": "retry", @@ -50726,21 +50714,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "recreate_instances" + "shortName": "insert" }, - "description": "Sample for RecreateInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_recreate_instances_sync.py", + "description": "Sample for Insert", + "file": "compute_v1beta_generated_region_instance_group_managers_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_RecreateInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -50750,22 +50738,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, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_recreate_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_insert_sync.py" }, { "canonical": true, @@ -50774,19 +50762,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.resize_advanced", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.list_errors", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ResizeAdvanced", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ListErrors", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ResizeAdvanced" + "shortName": "ListErrors" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ResizeAdvancedRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.ListErrorsRegionInstanceGroupManagersRequest" }, { "name": "project", @@ -50800,10 +50788,6 @@ "name": "instance_group_manager", "type": "str" }, - { - "name": "region_instance_group_managers_resize_advanced_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersResizeAdvancedRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -50817,22 +50801,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "resize_advanced" + "resultType": "google.cloud.compute_v1beta.services.region_instance_group_managers.pagers.ListErrorsPager", + "shortName": "list_errors" }, - "description": "Sample for ResizeAdvanced", - "file": "compute_v1beta_generated_region_instance_group_managers_resize_advanced_sync.py", + "description": "Sample for ListErrors", + "file": "compute_v1beta_generated_region_instance_group_managers_list_errors_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ResizeAdvanced_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ListErrors_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -50852,12 +50836,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 55, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_resize_advanced_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_list_errors_sync.py" }, { "canonical": true, @@ -50866,19 +50850,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.resize", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.list_managed_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Resize", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ListManagedInstances", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Resize" + "shortName": "ListManagedInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ResizeRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.ListManagedInstancesRegionInstanceGroupManagersRequest" }, { "name": "project", @@ -50892,10 +50876,6 @@ "name": "instance_group_manager", "type": "str" }, - { - "name": "size", - "type": "int" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -50909,14 +50889,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "resize" + "resultType": "google.cloud.compute_v1beta.services.region_instance_group_managers.pagers.ListManagedInstancesPager", + "shortName": "list_managed_instances" }, - "description": "Sample for Resize", - "file": "compute_v1beta_generated_region_instance_group_managers_resize_sync.py", + "description": "Sample for ListManagedInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_list_managed_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Resize_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ListManagedInstances_sync", "segments": [ { "end": 54, @@ -50934,22 +50914,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 55, - "start": 52, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_resize_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_list_managed_instances_sync.py" }, { "canonical": true, @@ -50958,19 +50938,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.resume_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.list_per_instance_configs", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ResumeInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ListPerInstanceConfigs", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ResumeInstances" + "shortName": "ListPerInstanceConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ResumeInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.ListPerInstanceConfigsRegionInstanceGroupManagersRequest" }, { "name": "project", @@ -50984,10 +50964,6 @@ "name": "instance_group_manager", "type": "str" }, - { - "name": "region_instance_group_managers_resume_instances_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersResumeInstancesRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -51001,22 +50977,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "resume_instances" + "resultType": "google.cloud.compute_v1beta.services.region_instance_group_managers.pagers.ListPerInstanceConfigsPager", + "shortName": "list_per_instance_configs" }, - "description": "Sample for ResumeInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_resume_instances_sync.py", + "description": "Sample for ListPerInstanceConfigs", + "file": "compute_v1beta_generated_region_instance_group_managers_list_per_instance_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ResumeInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ListPerInstanceConfigs_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -51036,12 +51012,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 55, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_resume_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_list_per_instance_configs_sync.py" }, { "canonical": true, @@ -51050,19 +51026,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.set_auto_healing_policies", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.SetAutoHealingPolicies", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.List", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "SetAutoHealingPolicies" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.SetAutoHealingPoliciesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.ListRegionInstanceGroupManagersRequest" }, { "name": "project", @@ -51072,14 +51048,6 @@ "name": "region", "type": "str" }, - { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "region_instance_group_managers_set_auto_healing_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersSetAutoHealingRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -51093,14 +51061,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_auto_healing_policies" + "resultType": "google.cloud.compute_v1beta.services.region_instance_group_managers.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for SetAutoHealingPolicies", - "file": "compute_v1beta_generated_region_instance_group_managers_set_auto_healing_policies_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_region_instance_group_managers_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_SetAutoHealingPolicies_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_List_sync", "segments": [ { "end": 53, @@ -51118,22 +51086,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_v1beta_generated_region_instance_group_managers_set_auto_healing_policies_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_list_sync.py" }, { "canonical": true, @@ -51142,19 +51110,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.set_instance_template", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.patch_per_instance_configs", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.SetInstanceTemplate", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.PatchPerInstanceConfigs", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "SetInstanceTemplate" + "shortName": "PatchPerInstanceConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.SetInstanceTemplateRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51169,8 +51137,8 @@ "type": "str" }, { - "name": "region_instance_group_managers_set_template_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersSetTemplateRequest" + "name": "region_instance_group_manager_patch_instance_config_req_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagerPatchInstanceConfigReq" }, { "name": "retry", @@ -51186,13 +51154,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_instance_template" + "shortName": "patch_per_instance_configs" }, - "description": "Sample for SetInstanceTemplate", - "file": "compute_v1beta_generated_region_instance_group_managers_set_instance_template_sync.py", + "description": "Sample for PatchPerInstanceConfigs", + "file": "compute_v1beta_generated_region_instance_group_managers_patch_per_instance_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_SetInstanceTemplate_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_PatchPerInstanceConfigs_sync", "segments": [ { "end": 53, @@ -51225,7 +51193,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_set_instance_template_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_patch_per_instance_configs_sync.py" }, { "canonical": true, @@ -51234,19 +51202,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.set_target_pools", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.patch", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.SetTargetPools", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Patch", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "SetTargetPools" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.SetTargetPoolsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.PatchRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51261,8 +51229,8 @@ "type": "str" }, { - "name": "region_instance_group_managers_set_target_pools_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersSetTargetPoolsRequest" + "name": "instance_group_manager_resource", + "type": "google.cloud.compute_v1beta.types.InstanceGroupManager" }, { "name": "retry", @@ -51278,13 +51246,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_target_pools" + "shortName": "patch" }, - "description": "Sample for SetTargetPools", - "file": "compute_v1beta_generated_region_instance_group_managers_set_target_pools_sync.py", + "description": "Sample for Patch", + "file": "compute_v1beta_generated_region_instance_group_managers_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_SetTargetPools_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Patch_sync", "segments": [ { "end": 53, @@ -51317,7 +51285,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_set_target_pools_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_patch_sync.py" }, { "canonical": true, @@ -51326,19 +51294,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.start_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.recreate_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.StartInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.RecreateInstances", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "StartInstances" + "shortName": "RecreateInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.StartInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.RecreateInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51353,8 +51321,8 @@ "type": "str" }, { - "name": "region_instance_group_managers_start_instances_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersStartInstancesRequest" + "name": "region_instance_group_managers_recreate_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersRecreateRequest" }, { "name": "retry", @@ -51370,13 +51338,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "start_instances" + "shortName": "recreate_instances" }, - "description": "Sample for StartInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_start_instances_sync.py", + "description": "Sample for RecreateInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_recreate_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_StartInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_RecreateInstances_sync", "segments": [ { "end": 53, @@ -51409,7 +51377,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_start_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_recreate_instances_sync.py" }, { "canonical": true, @@ -51418,19 +51386,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.stop_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.resize_advanced", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.StopInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ResizeAdvanced", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "StopInstances" + "shortName": "ResizeAdvanced" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.StopInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.ResizeAdvancedRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51445,8 +51413,8 @@ "type": "str" }, { - "name": "region_instance_group_managers_stop_instances_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersStopInstancesRequest" + "name": "region_instance_group_managers_resize_advanced_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersResizeAdvancedRequest" }, { "name": "retry", @@ -51462,13 +51430,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "stop_instances" + "shortName": "resize_advanced" }, - "description": "Sample for StopInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_stop_instances_sync.py", + "description": "Sample for ResizeAdvanced", + "file": "compute_v1beta_generated_region_instance_group_managers_resize_advanced_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_StopInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ResizeAdvanced_sync", "segments": [ { "end": 53, @@ -51501,7 +51469,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_stop_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_resize_advanced_sync.py" }, { "canonical": true, @@ -51510,19 +51478,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.suspend_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.resize", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.SuspendInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Resize", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "SuspendInstances" + "shortName": "Resize" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.SuspendInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.ResizeRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51537,8 +51505,8 @@ "type": "str" }, { - "name": "region_instance_group_managers_suspend_instances_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersSuspendInstancesRequest" + "name": "size", + "type": "int" }, { "name": "retry", @@ -51554,21 +51522,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "suspend_instances" + "shortName": "resize" }, - "description": "Sample for SuspendInstances", - "file": "compute_v1beta_generated_region_instance_group_managers_suspend_instances_sync.py", + "description": "Sample for Resize", + "file": "compute_v1beta_generated_region_instance_group_managers_resize_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_SuspendInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Resize_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -51578,22 +51546,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_suspend_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_resize_sync.py" }, { "canonical": true, @@ -51602,19 +51570,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.resume_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.ResumeInstances", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "TestIamPermissions" + "shortName": "ResumeInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.ResumeInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51625,12 +51593,12 @@ "type": "str" }, { - "name": "resource", + "name": "instance_group_manager", "type": "str" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1beta.types.TestPermissionsRequest" + "name": "region_instance_group_managers_resume_instances_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersResumeInstancesRequest" }, { "name": "retry", @@ -51645,14 +51613,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "resume_instances" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1beta_generated_region_instance_group_managers_test_iam_permissions_sync.py", + "description": "Sample for ResumeInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_resume_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_TestIamPermissions_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_ResumeInstances_sync", "segments": [ { "end": 53, @@ -51685,7 +51653,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_test_iam_permissions_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_resume_instances_sync.py" }, { "canonical": true, @@ -51694,19 +51662,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.update_per_instance_configs", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.set_auto_healing_policies", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.UpdatePerInstanceConfigs", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.SetAutoHealingPolicies", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "UpdatePerInstanceConfigs" + "shortName": "SetAutoHealingPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.SetAutoHealingPoliciesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51721,8 +51689,8 @@ "type": "str" }, { - "name": "region_instance_group_manager_update_instance_config_req_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagerUpdateInstanceConfigReq" + "name": "region_instance_group_managers_set_auto_healing_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersSetAutoHealingRequest" }, { "name": "retry", @@ -51738,13 +51706,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update_per_instance_configs" + "shortName": "set_auto_healing_policies" }, - "description": "Sample for UpdatePerInstanceConfigs", - "file": "compute_v1beta_generated_region_instance_group_managers_update_per_instance_configs_sync.py", + "description": "Sample for SetAutoHealingPolicies", + "file": "compute_v1beta_generated_region_instance_group_managers_set_auto_healing_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_UpdatePerInstanceConfigs_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_SetAutoHealingPolicies_sync", "segments": [ { "end": 53, @@ -51777,7 +51745,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_update_per_instance_configs_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_set_auto_healing_policies_sync.py" }, { "canonical": true, @@ -51786,19 +51754,19 @@ "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.update", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.set_instance_template", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Update", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.SetInstanceTemplate", "service": { "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Update" + "shortName": "SetInstanceTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.UpdateRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1beta.types.SetInstanceTemplateRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51813,8 +51781,8 @@ "type": "str" }, { - "name": "instance_group_manager_resource", - "type": "google.cloud.compute_v1beta.types.InstanceGroupManager" + "name": "region_instance_group_managers_set_template_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersSetTemplateRequest" }, { "name": "retry", @@ -51830,13 +51798,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update" + "shortName": "set_instance_template" }, - "description": "Sample for Update", - "file": "compute_v1beta_generated_region_instance_group_managers_update_sync.py", + "description": "Sample for SetInstanceTemplate", + "file": "compute_v1beta_generated_region_instance_group_managers_set_instance_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Update_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_SetInstanceTemplate_sync", "segments": [ { "end": 53, @@ -51869,28 +51837,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_group_managers_update_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_set_instance_template_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.get", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.set_target_pools", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.Get", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.SetTargetPools", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Get" + "shortName": "SetTargetPools" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionInstanceGroupRequest" + "type": "google.cloud.compute_v1beta.types.SetTargetPoolsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51901,9 +51869,13 @@ "type": "str" }, { - "name": "instance_group", + "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_managers_set_target_pools_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersSetTargetPoolsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -51917,14 +51889,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.InstanceGroup", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_target_pools" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_region_instance_groups_get_sync.py", + "description": "Sample for SetTargetPools", + "file": "compute_v1beta_generated_region_instance_group_managers_set_target_pools_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroups_Get_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_SetTargetPools_sync", "segments": [ { "end": 53, @@ -51957,28 +51929,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_groups_get_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_set_target_pools_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.list_instances", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.start_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.ListInstances", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.StartInstances", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ListInstances" + "shortName": "StartInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListInstancesRegionInstanceGroupsRequest" + "type": "google.cloud.compute_v1beta.types.StartInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -51989,12 +51961,12 @@ "type": "str" }, { - "name": "instance_group", + "name": "instance_group_manager", "type": "str" }, { - "name": "region_instance_groups_list_instances_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupsListInstancesRequest" + "name": "region_instance_group_managers_start_instances_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersStartInstancesRequest" }, { "name": "retry", @@ -52009,22 +51981,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instance_groups.pagers.ListInstancesPager", - "shortName": "list_instances" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "start_instances" }, - "description": "Sample for ListInstances", - "file": "compute_v1beta_generated_region_instance_groups_list_instances_sync.py", + "description": "Sample for StartInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_start_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroups_ListInstances_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_StartInstances_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -52044,33 +52016,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_groups_list_instances_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_start_instances_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.list", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.stop_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.List", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.StopInstances", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "List" + "shortName": "StopInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionInstanceGroupsRequest" + "type": "google.cloud.compute_v1beta.types.StopInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -52080,6 +52052,14 @@ "name": "region", "type": "str" }, + { + "name": "instance_group_manager", + "type": "str" + }, + { + "name": "region_instance_group_managers_stop_instances_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersStopInstancesRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -52093,14 +52073,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instance_groups.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "stop_instances" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_region_instance_groups_list_sync.py", + "description": "Sample for StopInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_stop_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroups_List_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_StopInstances_sync", "segments": [ { "end": 53, @@ -52118,43 +52098,43 @@ "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_v1beta_generated_region_instance_groups_list_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_stop_instances_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.set_named_ports", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.suspend_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.SetNamedPorts", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.SuspendInstances", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "SetNamedPorts" + "shortName": "SuspendInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.SetNamedPortsRegionInstanceGroupRequest" + "type": "google.cloud.compute_v1beta.types.SuspendInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -52165,12 +52145,12 @@ "type": "str" }, { - "name": "instance_group", + "name": "instance_group_manager", "type": "str" }, { - "name": "region_instance_groups_set_named_ports_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupsSetNamedPortsRequest" + "name": "region_instance_group_managers_suspend_instances_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagersSuspendInstancesRequest" }, { "name": "retry", @@ -52186,13 +52166,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_named_ports" + "shortName": "suspend_instances" }, - "description": "Sample for SetNamedPorts", - "file": "compute_v1beta_generated_region_instance_groups_set_named_ports_sync.py", + "description": "Sample for SuspendInstances", + "file": "compute_v1beta_generated_region_instance_group_managers_suspend_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroups_SetNamedPorts_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_SuspendInstances_sync", "segments": [ { "end": 53, @@ -52225,28 +52205,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_groups_set_named_ports_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_suspend_instances_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.TestIamPermissions", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionInstanceGroupRequest" + "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -52281,10 +52261,10 @@ "shortName": "test_iam_permissions" }, "description": "Sample for TestIamPermissions", - "file": "compute_v1beta_generated_region_instance_groups_test_iam_permissions_sync.py", + "file": "compute_v1beta_generated_region_instance_group_managers_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceGroups_TestIamPermissions_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -52317,28 +52297,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_groups_test_iam_permissions_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient", - "shortName": "RegionInstanceTemplatesClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient.delete", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.update_per_instance_configs", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates.Delete", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.UpdatePerInstanceConfigs", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates", - "shortName": "RegionInstanceTemplates" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Delete" + "shortName": "UpdatePerInstanceConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteRegionInstanceTemplateRequest" + "type": "google.cloud.compute_v1beta.types.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -52349,9 +52329,13 @@ "type": "str" }, { - "name": "instance_template", + "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_manager_update_instance_config_req_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupManagerUpdateInstanceConfigReq" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -52366,13 +52350,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "update_per_instance_configs" }, - "description": "Sample for Delete", - "file": "compute_v1beta_generated_region_instance_templates_delete_sync.py", + "description": "Sample for UpdatePerInstanceConfigs", + "file": "compute_v1beta_generated_region_instance_group_managers_update_per_instance_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceTemplates_Delete_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_UpdatePerInstanceConfigs_sync", "segments": [ { "end": 53, @@ -52405,28 +52389,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_templates_delete_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_update_per_instance_configs_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient", - "shortName": "RegionInstanceTemplatesClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient.get", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupManagersClient.update", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates.Get", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers.Update", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates", - "shortName": "RegionInstanceTemplates" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Get" + "shortName": "Update" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionInstanceTemplateRequest" + "type": "google.cloud.compute_v1beta.types.UpdateRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -52437,9 +52421,13 @@ "type": "str" }, { - "name": "instance_template", + "name": "instance_group_manager", "type": "str" }, + { + "name": "instance_group_manager_resource", + "type": "google.cloud.compute_v1beta.types.InstanceGroupManager" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -52453,14 +52441,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.InstanceTemplate", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_region_instance_templates_get_sync.py", + "description": "Sample for Update", + "file": "compute_v1beta_generated_region_instance_group_managers_update_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceTemplates_Get_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroupManagers_Update_sync", "segments": [ { "end": 53, @@ -52493,28 +52481,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_templates_get_sync.py" + "title": "compute_v1beta_generated_region_instance_group_managers_update_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient", - "shortName": "RegionInstanceTemplatesClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient.insert", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates.Insert", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.Get", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates", - "shortName": "RegionInstanceTemplates" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" }, - "shortName": "Insert" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertRegionInstanceTemplateRequest" + "type": "google.cloud.compute_v1beta.types.GetRegionInstanceGroupRequest" }, { "name": "project", @@ -52525,8 +52513,8 @@ "type": "str" }, { - "name": "instance_template_resource", - "type": "google.cloud.compute_v1beta.types.InstanceTemplate" + "name": "instance_group", + "type": "str" }, { "name": "retry", @@ -52541,22 +52529,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1beta.types.InstanceGroup", + "shortName": "get" }, - "description": "Sample for Insert", - "file": "compute_v1beta_generated_region_instance_templates_insert_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_instance_groups_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceTemplates_Insert_sync", + "regionTag": "compute_v1beta_generated_RegionInstanceGroups_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -52566,43 +52554,43 @@ "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_v1beta_generated_region_instance_templates_insert_sync.py" + "title": "compute_v1beta_generated_region_instance_groups_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient", - "shortName": "RegionInstanceTemplatesClient" + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient.list", + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.list_instances", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates.List", + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.ListInstances", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates", - "shortName": "RegionInstanceTemplates" + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" }, - "shortName": "List" + "shortName": "ListInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionInstanceTemplatesRequest" + "type": "google.cloud.compute_v1beta.types.ListInstancesRegionInstanceGroupsRequest" }, { "name": "project", @@ -52613,8 +52601,1780 @@ "type": "str" }, { - "name": "retry", - "type": "google.api_core.retry.Retry" + "name": "instance_group", + "type": "str" + }, + { + "name": "region_instance_groups_list_instances_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupsListInstancesRequest" + }, + { + "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_v1beta.services.region_instance_groups.pagers.ListInstancesPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "compute_v1beta_generated_region_instance_groups_list_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstanceGroups_ListInstances_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_v1beta_generated_region_instance_groups_list_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.List", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListRegionInstanceGroupsRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "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_v1beta.services.region_instance_groups.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_region_instance_groups_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstanceGroups_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_v1beta_generated_region_instance_groups_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.set_named_ports", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.SetNamedPorts", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" + }, + "shortName": "SetNamedPorts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.SetNamedPortsRegionInstanceGroupRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "instance_group", + "type": "str" + }, + { + "name": "region_instance_groups_set_named_ports_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionInstanceGroupsSetNamedPortsRequest" + }, + { + "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": "set_named_ports" + }, + "description": "Sample for SetNamedPorts", + "file": "compute_v1beta_generated_region_instance_groups_set_named_ports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstanceGroups_SetNamedPorts_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_v1beta_generated_region_instance_groups_set_named_ports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstanceGroupsClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups.TestIamPermissions", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionInstanceGroupRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1beta.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_v1beta.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "compute_v1beta_generated_region_instance_groups_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstanceGroups_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_v1beta_generated_region_instance_groups_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient", + "shortName": "RegionInstanceTemplatesClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient.delete", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates.Delete", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates", + "shortName": "RegionInstanceTemplates" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.DeleteRegionInstanceTemplateRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "instance_template", + "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_v1beta_generated_region_instance_templates_delete_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstanceTemplates_Delete_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_v1beta_generated_region_instance_templates_delete_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient", + "shortName": "RegionInstanceTemplatesClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates", + "shortName": "RegionInstanceTemplates" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetRegionInstanceTemplateRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "instance_template", + "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_v1beta.types.InstanceTemplate", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_instance_templates_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstanceTemplates_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_v1beta_generated_region_instance_templates_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient", + "shortName": "RegionInstanceTemplatesClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient.insert", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates.Insert", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates", + "shortName": "RegionInstanceTemplates" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.InsertRegionInstanceTemplateRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "instance_template_resource", + "type": "google.cloud.compute_v1beta.types.InstanceTemplate" + }, + { + "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_v1beta_generated_region_instance_templates_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstanceTemplates_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_v1beta_generated_region_instance_templates_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient", + "shortName": "RegionInstanceTemplatesClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstanceTemplatesClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates.List", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstanceTemplates", + "shortName": "RegionInstanceTemplates" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListRegionInstanceTemplatesRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "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_v1beta.services.region_instance_templates.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_region_instance_templates_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstanceTemplates_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_v1beta_generated_region_instance_templates_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstancesClient", + "shortName": "RegionInstancesClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstancesClient.bulk_insert", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstances.BulkInsert", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstances", + "shortName": "RegionInstances" + }, + "shortName": "BulkInsert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.BulkInsertRegionInstanceRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "bulk_insert_instance_resource_resource", + "type": "google.cloud.compute_v1beta.types.BulkInsertInstanceResource" + }, + { + "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": "bulk_insert" + }, + "description": "Sample for BulkInsert", + "file": "compute_v1beta_generated_region_instances_bulk_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstances_BulkInsert_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_v1beta_generated_region_instances_bulk_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.delete", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.Delete", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.DeleteRegionInstantSnapshotRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "instant_snapshot", + "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_v1beta_generated_region_instant_snapshots_delete_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_Delete_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_v1beta_generated_region_instant_snapshots_delete_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.get_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.GetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetIamPolicyRegionInstantSnapshotRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "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_v1beta.types.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "compute_v1beta_generated_region_instant_snapshots_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_GetIamPolicy_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_v1beta_generated_region_instant_snapshots_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetRegionInstantSnapshotRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "instant_snapshot", + "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_v1beta.types.InstantSnapshot", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_instant_snapshots_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_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_v1beta_generated_region_instant_snapshots_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.insert", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.Insert", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.InsertRegionInstantSnapshotRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "instant_snapshot_resource", + "type": "google.cloud.compute_v1beta.types.InstantSnapshot" + }, + { + "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_v1beta_generated_region_instant_snapshots_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_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_v1beta_generated_region_instant_snapshots_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.List", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListRegionInstantSnapshotsRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "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_v1beta.services.region_instant_snapshots.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_region_instant_snapshots_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_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_v1beta_generated_region_instant_snapshots_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.set_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.SetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.SetIamPolicyRegionInstantSnapshotRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionSetPolicyRequest" + }, + { + "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_v1beta.types.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "compute_v1beta_generated_region_instant_snapshots_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_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_v1beta_generated_region_instant_snapshots_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.set_labels", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.SetLabels", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" + }, + "shortName": "SetLabels" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.SetLabelsRegionInstantSnapshotRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "region_set_labels_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionSetLabelsRequest" + }, + { + "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": "set_labels" + }, + "description": "Sample for SetLabels", + "file": "compute_v1beta_generated_region_instant_snapshots_set_labels_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_SetLabels_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_v1beta_generated_region_instant_snapshots_set_labels_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.TestIamPermissions", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionInstantSnapshotRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1beta.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_v1beta.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "compute_v1beta_generated_region_instant_snapshots_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_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_v1beta_generated_region_instant_snapshots_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient", + "shortName": "RegionMultiMigsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient.delete", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigs.Delete", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigs", + "shortName": "RegionMultiMigs" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.DeleteRegionMultiMigRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "multi_mig", + "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_v1beta_generated_region_multi_migs_delete_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionMultiMigs_Delete_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_v1beta_generated_region_multi_migs_delete_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient", + "shortName": "RegionMultiMigsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigs.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigs", + "shortName": "RegionMultiMigs" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetRegionMultiMigRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "multi_mig", + "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_v1beta.types.MultiMig", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_multi_migs_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionMultiMigs_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_v1beta_generated_region_multi_migs_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient", + "shortName": "RegionMultiMigsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient.insert", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigs.Insert", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigs", + "shortName": "RegionMultiMigs" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.InsertRegionMultiMigRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "multi_mig_resource", + "type": "google.cloud.compute_v1beta.types.MultiMig" + }, + { + "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_v1beta_generated_region_multi_migs_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionMultiMigs_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_v1beta_generated_region_multi_migs_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient", + "shortName": "RegionMultiMigsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigs.List", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigs", + "shortName": "RegionMultiMigs" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListRegionMultiMigsRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" }, { "name": "timeout", @@ -52625,14 +54385,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instance_templates.pagers.ListPager", + "resultType": "google.cloud.compute_v1beta.services.region_multi_migs.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1beta_generated_region_instance_templates_list_sync.py", + "file": "compute_v1beta_generated_region_multi_migs_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstanceTemplates_List_sync", + "regionTag": "compute_v1beta_generated_RegionMultiMigs_List_sync", "segments": [ { "end": 53, @@ -52665,28 +54425,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instance_templates_list_sync.py" + "title": "compute_v1beta_generated_region_multi_migs_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstancesClient", - "shortName": "RegionInstancesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", + "shortName": "RegionNetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstancesClient.bulk_insert", + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.attach_network_endpoints", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstances.BulkInsert", + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.AttachNetworkEndpoints", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstances", - "shortName": "RegionInstances" + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", + "shortName": "RegionNetworkEndpointGroups" }, - "shortName": "BulkInsert" + "shortName": "AttachNetworkEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.BulkInsertRegionInstanceRequest" + "type": "google.cloud.compute_v1beta.types.AttachNetworkEndpointsRegionNetworkEndpointGroupRequest" }, { "name": "project", @@ -52697,8 +54457,12 @@ "type": "str" }, { - "name": "bulk_insert_instance_resource_resource", - "type": "google.cloud.compute_v1beta.types.BulkInsertInstanceResource" + "name": "network_endpoint_group", + "type": "str" + }, + { + "name": "region_network_endpoint_groups_attach_endpoints_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionNetworkEndpointGroupsAttachEndpointsRequest" }, { "name": "retry", @@ -52714,21 +54478,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "bulk_insert" + "shortName": "attach_network_endpoints" }, - "description": "Sample for BulkInsert", - "file": "compute_v1beta_generated_region_instances_bulk_insert_sync.py", + "description": "Sample for AttachNetworkEndpoints", + "file": "compute_v1beta_generated_region_network_endpoint_groups_attach_network_endpoints_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstances_BulkInsert_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_AttachNetworkEndpoints_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -52738,43 +54502,43 @@ "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_v1beta_generated_region_instances_bulk_insert_sync.py" + "title": "compute_v1beta_generated_region_network_endpoint_groups_attach_network_endpoints_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", - "shortName": "RegionInstantSnapshotsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", + "shortName": "RegionNetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.delete", + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.Delete", + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.Delete", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", - "shortName": "RegionInstantSnapshots" + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", + "shortName": "RegionNetworkEndpointGroups" }, "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteRegionInstantSnapshotRequest" + "type": "google.cloud.compute_v1beta.types.DeleteRegionNetworkEndpointGroupRequest" }, { "name": "project", @@ -52785,7 +54549,7 @@ "type": "str" }, { - "name": "instant_snapshot", + "name": "network_endpoint_group", "type": "str" }, { @@ -52805,10 +54569,10 @@ "shortName": "delete" }, "description": "Sample for Delete", - "file": "compute_v1beta_generated_region_instant_snapshots_delete_sync.py", + "file": "compute_v1beta_generated_region_network_endpoint_groups_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_Delete_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_Delete_sync", "segments": [ { "end": 53, @@ -52841,28 +54605,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instant_snapshots_delete_sync.py" + "title": "compute_v1beta_generated_region_network_endpoint_groups_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", - "shortName": "RegionInstantSnapshotsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", + "shortName": "RegionNetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.get_iam_policy", + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.detach_network_endpoints", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.DetachNetworkEndpoints", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", - "shortName": "RegionInstantSnapshots" + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", + "shortName": "RegionNetworkEndpointGroups" }, - "shortName": "GetIamPolicy" + "shortName": "DetachNetworkEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetIamPolicyRegionInstantSnapshotRequest" + "type": "google.cloud.compute_v1beta.types.DetachNetworkEndpointsRegionNetworkEndpointGroupRequest" }, { "name": "project", @@ -52873,9 +54637,13 @@ "type": "str" }, { - "name": "resource", + "name": "network_endpoint_group", "type": "str" }, + { + "name": "region_network_endpoint_groups_detach_endpoints_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionNetworkEndpointGroupsDetachEndpointsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -52889,14 +54657,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "detach_network_endpoints" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1beta_generated_region_instant_snapshots_get_iam_policy_sync.py", + "description": "Sample for DetachNetworkEndpoints", + "file": "compute_v1beta_generated_region_network_endpoint_groups_detach_network_endpoints_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_GetIamPolicy_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_DetachNetworkEndpoints_sync", "segments": [ { "end": 53, @@ -52929,28 +54697,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instant_snapshots_get_iam_policy_sync.py" + "title": "compute_v1beta_generated_region_network_endpoint_groups_detach_network_endpoints_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", - "shortName": "RegionInstantSnapshotsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", + "shortName": "RegionNetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.get", + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.Get", + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.Get", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", - "shortName": "RegionInstantSnapshots" + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", + "shortName": "RegionNetworkEndpointGroups" }, "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionInstantSnapshotRequest" + "type": "google.cloud.compute_v1beta.types.GetRegionNetworkEndpointGroupRequest" }, { "name": "project", @@ -52961,7 +54729,7 @@ "type": "str" }, { - "name": "instant_snapshot", + "name": "network_endpoint_group", "type": "str" }, { @@ -52977,14 +54745,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.InstantSnapshot", + "resultType": "google.cloud.compute_v1beta.types.NetworkEndpointGroup", "shortName": "get" }, "description": "Sample for Get", - "file": "compute_v1beta_generated_region_instant_snapshots_get_sync.py", + "file": "compute_v1beta_generated_region_network_endpoint_groups_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_Get_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_Get_sync", "segments": [ { "end": 53, @@ -53017,28 +54785,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instant_snapshots_get_sync.py" + "title": "compute_v1beta_generated_region_network_endpoint_groups_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", - "shortName": "RegionInstantSnapshotsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", + "shortName": "RegionNetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.insert", + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.insert", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.Insert", + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.Insert", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", - "shortName": "RegionInstantSnapshots" + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", + "shortName": "RegionNetworkEndpointGroups" }, "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertRegionInstantSnapshotRequest" + "type": "google.cloud.compute_v1beta.types.InsertRegionNetworkEndpointGroupRequest" }, { "name": "project", @@ -53049,8 +54817,8 @@ "type": "str" }, { - "name": "instant_snapshot_resource", - "type": "google.cloud.compute_v1beta.types.InstantSnapshot" + "name": "network_endpoint_group_resource", + "type": "google.cloud.compute_v1beta.types.NetworkEndpointGroup" }, { "name": "retry", @@ -53069,10 +54837,10 @@ "shortName": "insert" }, "description": "Sample for Insert", - "file": "compute_v1beta_generated_region_instant_snapshots_insert_sync.py", + "file": "compute_v1beta_generated_region_network_endpoint_groups_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_Insert_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_Insert_sync", "segments": [ { "end": 52, @@ -53105,28 +54873,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instant_snapshots_insert_sync.py" + "title": "compute_v1beta_generated_region_network_endpoint_groups_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", - "shortName": "RegionInstantSnapshotsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", + "shortName": "RegionNetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.list", + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.list_network_endpoints", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.List", + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.ListNetworkEndpoints", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", - "shortName": "RegionInstantSnapshots" + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", + "shortName": "RegionNetworkEndpointGroups" }, - "shortName": "List" + "shortName": "ListNetworkEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionInstantSnapshotsRequest" + "type": "google.cloud.compute_v1beta.types.ListNetworkEndpointsRegionNetworkEndpointGroupsRequest" }, { "name": "project", @@ -53136,6 +54904,10 @@ "name": "region", "type": "str" }, + { + "name": "network_endpoint_group", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -53149,22 +54921,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_instant_snapshots.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1beta.services.region_network_endpoint_groups.pagers.ListNetworkEndpointsPager", + "shortName": "list_network_endpoints" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_region_instant_snapshots_list_sync.py", + "description": "Sample for ListNetworkEndpoints", + "file": "compute_v1beta_generated_region_network_endpoint_groups_list_network_endpoints_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_List_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_ListNetworkEndpoints_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -53174,59 +54946,51 @@ "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, + "end": 55, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instant_snapshots_list_sync.py" + "title": "compute_v1beta_generated_region_network_endpoint_groups_list_network_endpoints_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", - "shortName": "RegionInstantSnapshotsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", + "shortName": "RegionNetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.set_iam_policy", + "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.SetIamPolicy", + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.List", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", - "shortName": "RegionInstantSnapshots" + "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", + "shortName": "RegionNetworkEndpointGroups" }, - "shortName": "SetIamPolicy" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.SetIamPolicyRegionInstantSnapshotRequest" + "type": "google.cloud.compute_v1beta.types.ListRegionNetworkEndpointGroupsRequest" }, { "name": "project", "type": "str" }, { - "name": "region", - "type": "str" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "region_set_policy_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionSetPolicyRequest" + "name": "region", + "type": "str" }, { "name": "retry", @@ -53241,14 +55005,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.cloud.compute_v1beta.services.region_network_endpoint_groups.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1beta_generated_region_instant_snapshots_set_iam_policy_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_region_network_endpoint_groups_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_SetIamPolicy_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_List_sync", "segments": [ { "end": 53, @@ -53266,43 +55030,43 @@ "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_v1beta_generated_region_instant_snapshots_set_iam_policy_sync.py" + "title": "compute_v1beta_generated_region_network_endpoint_groups_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", - "shortName": "RegionInstantSnapshotsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.set_labels", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.add_association", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.SetLabels", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.AddAssociation", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", - "shortName": "RegionInstantSnapshots" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "SetLabels" + "shortName": "AddAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.SetLabelsRegionInstantSnapshotRequest" + "type": "google.cloud.compute_v1beta.types.AddAssociationRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -53313,12 +55077,12 @@ "type": "str" }, { - "name": "resource", + "name": "firewall_policy", "type": "str" }, { - "name": "region_set_labels_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionSetLabelsRequest" + "name": "firewall_policy_association_resource", + "type": "google.cloud.compute_v1beta.types.FirewallPolicyAssociation" }, { "name": "retry", @@ -53334,13 +55098,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_labels" + "shortName": "add_association" }, - "description": "Sample for SetLabels", - "file": "compute_v1beta_generated_region_instant_snapshots_set_labels_sync.py", + "description": "Sample for AddAssociation", + "file": "compute_v1beta_generated_region_network_firewall_policies_add_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_SetLabels_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_AddAssociation_sync", "segments": [ { "end": 53, @@ -53373,28 +55137,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instant_snapshots_set_labels_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_add_association_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient", - "shortName": "RegionInstantSnapshotsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionInstantSnapshotsClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.add_rule", "method": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots.TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.AddRule", "service": { - "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshots", - "shortName": "RegionInstantSnapshots" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "TestIamPermissions" + "shortName": "AddRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionInstantSnapshotRequest" + "type": "google.cloud.compute_v1beta.types.AddRuleRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -53405,12 +55169,12 @@ "type": "str" }, { - "name": "resource", + "name": "firewall_policy", "type": "str" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1beta.types.TestPermissionsRequest" + "name": "firewall_policy_rule_resource", + "type": "google.cloud.compute_v1beta.types.FirewallPolicyRule" }, { "name": "retry", @@ -53425,14 +55189,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "add_rule" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1beta_generated_region_instant_snapshots_test_iam_permissions_sync.py", + "description": "Sample for AddRule", + "file": "compute_v1beta_generated_region_network_firewall_policies_add_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_TestIamPermissions_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_AddRule_sync", "segments": [ { "end": 53, @@ -53465,28 +55229,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_instant_snapshots_test_iam_permissions_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_add_rule_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient", - "shortName": "RegionMultiMigsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient.delete", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.clone_rules", "method": { - "fullName": "google.cloud.compute.v1beta.RegionMultiMigs.Delete", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.CloneRules", "service": { - "fullName": "google.cloud.compute.v1beta.RegionMultiMigs", - "shortName": "RegionMultiMigs" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "Delete" + "shortName": "CloneRules" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteRegionMultiMigRequest" + "type": "google.cloud.compute_v1beta.types.CloneRulesRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -53497,7 +55261,7 @@ "type": "str" }, { - "name": "multi_mig", + "name": "firewall_policy", "type": "str" }, { @@ -53514,13 +55278,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "clone_rules" }, - "description": "Sample for Delete", - "file": "compute_v1beta_generated_region_multi_migs_delete_sync.py", + "description": "Sample for CloneRules", + "file": "compute_v1beta_generated_region_network_firewall_policies_clone_rules_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionMultiMigs_Delete_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_CloneRules_sync", "segments": [ { "end": 53, @@ -53553,28 +55317,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_multi_migs_delete_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_clone_rules_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient", - "shortName": "RegionMultiMigsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient.get", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.RegionMultiMigs.Get", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.Delete", "service": { - "fullName": "google.cloud.compute.v1beta.RegionMultiMigs", - "shortName": "RegionMultiMigs" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "Get" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionMultiMigRequest" + "type": "google.cloud.compute_v1beta.types.DeleteRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -53585,7 +55349,7 @@ "type": "str" }, { - "name": "multi_mig", + "name": "firewall_policy", "type": "str" }, { @@ -53601,14 +55365,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.MultiMig", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_region_multi_migs_get_sync.py", + "description": "Sample for Delete", + "file": "compute_v1beta_generated_region_network_firewall_policies_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionMultiMigs_Get_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_Delete_sync", "segments": [ { "end": 53, @@ -53641,28 +55405,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_multi_migs_get_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient", - "shortName": "RegionMultiMigsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient.insert", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get_association", "method": { - "fullName": "google.cloud.compute.v1beta.RegionMultiMigs.Insert", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.GetAssociation", "service": { - "fullName": "google.cloud.compute.v1beta.RegionMultiMigs", - "shortName": "RegionMultiMigs" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "Insert" + "shortName": "GetAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertRegionMultiMigRequest" + "type": "google.cloud.compute_v1beta.types.GetAssociationRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -53673,8 +55437,8 @@ "type": "str" }, { - "name": "multi_mig_resource", - "type": "google.cloud.compute_v1beta.types.MultiMig" + "name": "firewall_policy", + "type": "str" }, { "name": "retry", @@ -53689,22 +55453,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1beta.types.FirewallPolicyAssociation", + "shortName": "get_association" }, - "description": "Sample for Insert", - "file": "compute_v1beta_generated_region_multi_migs_insert_sync.py", + "description": "Sample for GetAssociation", + "file": "compute_v1beta_generated_region_network_firewall_policies_get_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionMultiMigs_Insert_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_GetAssociation_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -53714,43 +55478,43 @@ "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_v1beta_generated_region_multi_migs_insert_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_get_association_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient", - "shortName": "RegionMultiMigsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionMultiMigsClient.list", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get_effective_firewalls", "method": { - "fullName": "google.cloud.compute.v1beta.RegionMultiMigs.List", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.GetEffectiveFirewalls", "service": { - "fullName": "google.cloud.compute.v1beta.RegionMultiMigs", - "shortName": "RegionMultiMigs" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "List" + "shortName": "GetEffectiveFirewalls" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionMultiMigsRequest" + "type": "google.cloud.compute_v1beta.types.GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -53760,6 +55524,10 @@ "name": "region", "type": "str" }, + { + "name": "network", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -53773,14 +55541,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_multi_migs.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1beta.types.RegionNetworkFirewallPoliciesGetEffectiveFirewallsResponse", + "shortName": "get_effective_firewalls" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_region_multi_migs_list_sync.py", + "description": "Sample for GetEffectiveFirewalls", + "file": "compute_v1beta_generated_region_network_firewall_policies_get_effective_firewalls_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionMultiMigs_List_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_GetEffectiveFirewalls_sync", "segments": [ { "end": 53, @@ -53798,43 +55566,43 @@ "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_v1beta_generated_region_multi_migs_list_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_get_effective_firewalls_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", - "shortName": "RegionNetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.attach_network_endpoints", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.AttachNetworkEndpoints", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", - "shortName": "RegionNetworkEndpointGroups" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "AttachNetworkEndpoints" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.AttachNetworkEndpointsRegionNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1beta.types.GetIamPolicyRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -53845,13 +55613,9 @@ "type": "str" }, { - "name": "network_endpoint_group", + "name": "resource", "type": "str" }, - { - "name": "region_network_endpoint_groups_attach_endpoints_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionNetworkEndpointGroupsAttachEndpointsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -53865,14 +55629,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "attach_network_endpoints" + "resultType": "google.cloud.compute_v1beta.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for AttachNetworkEndpoints", - "file": "compute_v1beta_generated_region_network_endpoint_groups_attach_network_endpoints_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1beta_generated_region_network_firewall_policies_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_AttachNetworkEndpoints_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_GetIamPolicy_sync", "segments": [ { "end": 53, @@ -53905,28 +55669,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_endpoint_groups_attach_network_endpoints_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_get_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", - "shortName": "RegionNetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.delete", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get_rule", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.Delete", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.GetRule", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", - "shortName": "RegionNetworkEndpointGroups" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "Delete" + "shortName": "GetRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteRegionNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1beta.types.GetRuleRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -53937,7 +55701,7 @@ "type": "str" }, { - "name": "network_endpoint_group", + "name": "firewall_policy", "type": "str" }, { @@ -53953,14 +55717,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1beta.types.FirewallPolicyRule", + "shortName": "get_rule" }, - "description": "Sample for Delete", - "file": "compute_v1beta_generated_region_network_endpoint_groups_delete_sync.py", + "description": "Sample for GetRule", + "file": "compute_v1beta_generated_region_network_firewall_policies_get_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_Delete_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_GetRule_sync", "segments": [ { "end": 53, @@ -53993,28 +55757,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_endpoint_groups_delete_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_get_rule_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", - "shortName": "RegionNetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.detach_network_endpoints", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.DetachNetworkEndpoints", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.Get", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", - "shortName": "RegionNetworkEndpointGroups" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "DetachNetworkEndpoints" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DetachNetworkEndpointsRegionNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1beta.types.GetRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54025,13 +55789,9 @@ "type": "str" }, { - "name": "network_endpoint_group", + "name": "firewall_policy", "type": "str" }, - { - "name": "region_network_endpoint_groups_detach_endpoints_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionNetworkEndpointGroupsDetachEndpointsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -54045,14 +55805,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "detach_network_endpoints" + "resultType": "google.cloud.compute_v1beta.types.FirewallPolicy", + "shortName": "get" }, - "description": "Sample for DetachNetworkEndpoints", - "file": "compute_v1beta_generated_region_network_endpoint_groups_detach_network_endpoints_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_network_firewall_policies_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_DetachNetworkEndpoints_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_Get_sync", "segments": [ { "end": 53, @@ -54085,28 +55845,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_endpoint_groups_detach_network_endpoints_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", - "shortName": "RegionNetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.get", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.insert", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.Get", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.Insert", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", - "shortName": "RegionNetworkEndpointGroups" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "Get" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1beta.types.InsertRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54117,8 +55877,8 @@ "type": "str" }, { - "name": "network_endpoint_group", - "type": "str" + "name": "firewall_policy_resource", + "type": "google.cloud.compute_v1beta.types.FirewallPolicy" }, { "name": "retry", @@ -54133,22 +55893,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.NetworkEndpointGroup", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_region_network_endpoint_groups_get_sync.py", + "description": "Sample for Insert", + "file": "compute_v1beta_generated_region_network_firewall_policies_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_Get_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -54158,43 +55918,43 @@ "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_v1beta_generated_region_network_endpoint_groups_get_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", - "shortName": "RegionNetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.insert", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.Insert", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.List", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", - "shortName": "RegionNetworkEndpointGroups" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "Insert" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertRegionNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1beta.types.ListRegionNetworkFirewallPoliciesRequest" }, { "name": "project", @@ -54204,10 +55964,6 @@ "name": "region", "type": "str" }, - { - "name": "network_endpoint_group_resource", - "type": "google.cloud.compute_v1beta.types.NetworkEndpointGroup" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -54221,22 +55977,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1beta.services.region_network_firewall_policies.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Insert", - "file": "compute_v1beta_generated_region_network_endpoint_groups_insert_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_region_network_firewall_policies_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_Insert_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_List_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -54256,33 +56012,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 54, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_endpoint_groups_insert_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", - "shortName": "RegionNetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.list_network_endpoints", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.patch_association", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.ListNetworkEndpoints", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.PatchAssociation", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", - "shortName": "RegionNetworkEndpointGroups" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "ListNetworkEndpoints" + "shortName": "PatchAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListNetworkEndpointsRegionNetworkEndpointGroupsRequest" + "type": "google.cloud.compute_v1beta.types.PatchAssociationRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54293,9 +56049,13 @@ "type": "str" }, { - "name": "network_endpoint_group", + "name": "firewall_policy", "type": "str" }, + { + "name": "firewall_policy_association_resource", + "type": "google.cloud.compute_v1beta.types.FirewallPolicyAssociation" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -54309,22 +56069,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_network_endpoint_groups.pagers.ListNetworkEndpointsPager", - "shortName": "list_network_endpoints" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch_association" }, - "description": "Sample for ListNetworkEndpoints", - "file": "compute_v1beta_generated_region_network_endpoint_groups_list_network_endpoints_sync.py", + "description": "Sample for PatchAssociation", + "file": "compute_v1beta_generated_region_network_firewall_policies_patch_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_ListNetworkEndpoints_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_PatchAssociation_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -54344,33 +56104,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_endpoint_groups_list_network_endpoints_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_patch_association_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient", - "shortName": "RegionNetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", + "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkEndpointGroupsClient.list", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.patch_rule", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups.List", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.PatchRule", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkEndpointGroups", - "shortName": "RegionNetworkEndpointGroups" + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", + "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "List" + "shortName": "PatchRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionNetworkEndpointGroupsRequest" + "type": "google.cloud.compute_v1beta.types.PatchRuleRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54380,6 +56140,14 @@ "name": "region", "type": "str" }, + { + "name": "firewall_policy", + "type": "str" + }, + { + "name": "firewall_policy_rule_resource", + "type": "google.cloud.compute_v1beta.types.FirewallPolicyRule" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -54393,14 +56161,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_network_endpoint_groups.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch_rule" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_region_network_endpoint_groups_list_sync.py", + "description": "Sample for PatchRule", + "file": "compute_v1beta_generated_region_network_firewall_policies_patch_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_List_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_PatchRule_sync", "segments": [ { "end": 53, @@ -54418,22 +56186,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_v1beta_generated_region_network_endpoint_groups_list_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_patch_rule_sync.py" }, { "canonical": true, @@ -54442,19 +56210,19 @@ "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.add_association", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.patch", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.AddAssociation", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.Patch", "service": { "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "AddAssociation" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.AddAssociationRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.PatchRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54469,8 +56237,8 @@ "type": "str" }, { - "name": "firewall_policy_association_resource", - "type": "google.cloud.compute_v1beta.types.FirewallPolicyAssociation" + "name": "firewall_policy_resource", + "type": "google.cloud.compute_v1beta.types.FirewallPolicy" }, { "name": "retry", @@ -54486,13 +56254,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_association" + "shortName": "patch" }, - "description": "Sample for AddAssociation", - "file": "compute_v1beta_generated_region_network_firewall_policies_add_association_sync.py", + "description": "Sample for Patch", + "file": "compute_v1beta_generated_region_network_firewall_policies_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_AddAssociation_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_Patch_sync", "segments": [ { "end": 53, @@ -54525,7 +56293,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_add_association_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_patch_sync.py" }, { "canonical": true, @@ -54534,19 +56302,19 @@ "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.add_rule", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.remove_association", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.AddRule", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.RemoveAssociation", "service": { "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "AddRule" + "shortName": "RemoveAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.AddRuleRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.RemoveAssociationRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54560,10 +56328,6 @@ "name": "firewall_policy", "type": "str" }, - { - "name": "firewall_policy_rule_resource", - "type": "google.cloud.compute_v1beta.types.FirewallPolicyRule" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -54578,13 +56342,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_rule" + "shortName": "remove_association" }, - "description": "Sample for AddRule", - "file": "compute_v1beta_generated_region_network_firewall_policies_add_rule_sync.py", + "description": "Sample for RemoveAssociation", + "file": "compute_v1beta_generated_region_network_firewall_policies_remove_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_AddRule_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_RemoveAssociation_sync", "segments": [ { "end": 53, @@ -54617,7 +56381,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_add_rule_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_remove_association_sync.py" }, { "canonical": true, @@ -54626,19 +56390,19 @@ "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.clone_rules", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.remove_rule", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.CloneRules", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.RemoveRule", "service": { "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "CloneRules" + "shortName": "RemoveRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.CloneRulesRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.RemoveRuleRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54666,13 +56430,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "clone_rules" + "shortName": "remove_rule" }, - "description": "Sample for CloneRules", - "file": "compute_v1beta_generated_region_network_firewall_policies_clone_rules_sync.py", + "description": "Sample for RemoveRule", + "file": "compute_v1beta_generated_region_network_firewall_policies_remove_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_CloneRules_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_RemoveRule_sync", "segments": [ { "end": 53, @@ -54705,7 +56469,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_clone_rules_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_remove_rule_sync.py" }, { "canonical": true, @@ -54714,19 +56478,19 @@ "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.delete", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.Delete", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.SetIamPolicy", "service": { "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "Delete" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.SetIamPolicyRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54737,9 +56501,13 @@ "type": "str" }, { - "name": "firewall_policy", + "name": "resource", "type": "str" }, + { + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionSetPolicyRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -54753,14 +56521,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1beta.types.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for Delete", - "file": "compute_v1beta_generated_region_network_firewall_policies_delete_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1beta_generated_region_network_firewall_policies_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_Delete_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -54793,7 +56561,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_delete_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_set_iam_policy_sync.py" }, { "canonical": true, @@ -54802,19 +56570,19 @@ "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", "shortName": "RegionNetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get_association", + "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.GetAssociation", + "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", "shortName": "RegionNetworkFirewallPolicies" }, - "shortName": "GetAssociation" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetAssociationRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionNetworkFirewallPolicyRequest" }, { "name": "project", @@ -54825,9 +56593,13 @@ "type": "str" }, { - "name": "firewall_policy", + "name": "resource", "type": "str" }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1beta.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -54841,14 +56613,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.FirewallPolicyAssociation", - "shortName": "get_association" + "resultType": "google.cloud.compute_v1beta.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for GetAssociation", - "file": "compute_v1beta_generated_region_network_firewall_policies_get_association_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1beta_generated_region_network_firewall_policies_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_GetAssociation_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -54881,28 +56653,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_get_association_sync.py" + "title": "compute_v1beta_generated_region_network_firewall_policies_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get_effective_firewalls", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.add_association", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.GetEffectiveFirewalls", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.AddAssociation", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "GetEffectiveFirewalls" + "shortName": "AddAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.AddAssociationRegionNetworkPolicyRequest" }, { "name": "project", @@ -54913,9 +56685,13 @@ "type": "str" }, { - "name": "network", + "name": "network_policy", "type": "str" }, + { + "name": "network_policy_association_resource", + "type": "google.cloud.compute_v1beta.types.NetworkPolicyAssociation" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -54929,14 +56705,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.RegionNetworkFirewallPoliciesGetEffectiveFirewallsResponse", - "shortName": "get_effective_firewalls" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "add_association" }, - "description": "Sample for GetEffectiveFirewalls", - "file": "compute_v1beta_generated_region_network_firewall_policies_get_effective_firewalls_sync.py", + "description": "Sample for AddAssociation", + "file": "compute_v1beta_generated_region_network_policies_add_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_GetEffectiveFirewalls_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_AddAssociation_sync", "segments": [ { "end": 53, @@ -54969,28 +56745,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_get_effective_firewalls_sync.py" + "title": "compute_v1beta_generated_region_network_policies_add_association_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get_iam_policy", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.add_traffic_classification_rule", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.AddTrafficClassificationRule", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "GetIamPolicy" + "shortName": "AddTrafficClassificationRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetIamPolicyRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.AddTrafficClassificationRuleRegionNetworkPolicyRequest" }, { "name": "project", @@ -55001,9 +56777,13 @@ "type": "str" }, { - "name": "resource", + "name": "network_policy", "type": "str" }, + { + "name": "network_policy_traffic_classification_rule_resource", + "type": "google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -55017,14 +56797,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "add_traffic_classification_rule" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1beta_generated_region_network_firewall_policies_get_iam_policy_sync.py", + "description": "Sample for AddTrafficClassificationRule", + "file": "compute_v1beta_generated_region_network_policies_add_traffic_classification_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_GetIamPolicy_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_AddTrafficClassificationRule_sync", "segments": [ { "end": 53, @@ -55057,41 +56837,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_get_iam_policy_sync.py" + "title": "compute_v1beta_generated_region_network_policies_add_traffic_classification_rule_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get_rule", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.GetRule", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "GetRule" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRuleRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.AggregatedListRegionNetworkPoliciesRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, - { - "name": "firewall_policy", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -55105,22 +56877,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.FirewallPolicyRule", - "shortName": "get_rule" + "resultType": "google.cloud.compute_v1beta.services.region_network_policies.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for GetRule", - "file": "compute_v1beta_generated_region_network_firewall_policies_get_rule_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1beta_generated_region_network_policies_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_GetRule_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_AggregatedList_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -55130,43 +56902,43 @@ "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_v1beta_generated_region_network_firewall_policies_get_rule_sync.py" + "title": "compute_v1beta_generated_region_network_policies_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.get", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.Get", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.Delete", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "Get" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.DeleteRegionNetworkPolicyRequest" }, { "name": "project", @@ -55177,7 +56949,7 @@ "type": "str" }, { - "name": "firewall_policy", + "name": "network_policy", "type": "str" }, { @@ -55193,14 +56965,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.FirewallPolicy", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_region_network_firewall_policies_get_sync.py", + "description": "Sample for Delete", + "file": "compute_v1beta_generated_region_network_policies_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_Get_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_Delete_sync", "segments": [ { "end": 53, @@ -55233,28 +57005,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_get_sync.py" + "title": "compute_v1beta_generated_region_network_policies_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.insert", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.get_association", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.Insert", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.GetAssociation", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "Insert" + "shortName": "GetAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.GetAssociationRegionNetworkPolicyRequest" }, { "name": "project", @@ -55265,8 +57037,8 @@ "type": "str" }, { - "name": "firewall_policy_resource", - "type": "google.cloud.compute_v1beta.types.FirewallPolicy" + "name": "network_policy", + "type": "str" }, { "name": "retry", @@ -55281,22 +57053,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1beta.types.NetworkPolicyAssociation", + "shortName": "get_association" }, - "description": "Sample for Insert", - "file": "compute_v1beta_generated_region_network_firewall_policies_insert_sync.py", + "description": "Sample for GetAssociation", + "file": "compute_v1beta_generated_region_network_policies_get_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_Insert_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_GetAssociation_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -55306,43 +57078,43 @@ "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_v1beta_generated_region_network_firewall_policies_insert_sync.py" + "title": "compute_v1beta_generated_region_network_policies_get_association_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.list", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.get_traffic_classification_rule", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.List", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.GetTrafficClassificationRule", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "List" + "shortName": "GetTrafficClassificationRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionNetworkFirewallPoliciesRequest" + "type": "google.cloud.compute_v1beta.types.GetTrafficClassificationRuleRegionNetworkPolicyRequest" }, { "name": "project", @@ -55352,6 +57124,10 @@ "name": "region", "type": "str" }, + { + "name": "network_policy", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -55365,14 +57141,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_network_firewall_policies.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule", + "shortName": "get_traffic_classification_rule" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_region_network_firewall_policies_list_sync.py", + "description": "Sample for GetTrafficClassificationRule", + "file": "compute_v1beta_generated_region_network_policies_get_traffic_classification_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_List_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_GetTrafficClassificationRule_sync", "segments": [ { "end": 53, @@ -55390,43 +57166,43 @@ "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_v1beta_generated_region_network_firewall_policies_list_sync.py" + "title": "compute_v1beta_generated_region_network_policies_get_traffic_classification_rule_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.patch_association", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.PatchAssociation", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.Get", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "PatchAssociation" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.PatchAssociationRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.GetRegionNetworkPolicyRequest" }, { "name": "project", @@ -55437,13 +57213,9 @@ "type": "str" }, { - "name": "firewall_policy", + "name": "network_policy", "type": "str" }, - { - "name": "firewall_policy_association_resource", - "type": "google.cloud.compute_v1beta.types.FirewallPolicyAssociation" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -55457,14 +57229,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch_association" + "resultType": "google.cloud.compute_v1beta.types.NetworkPolicy", + "shortName": "get" }, - "description": "Sample for PatchAssociation", - "file": "compute_v1beta_generated_region_network_firewall_policies_patch_association_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_network_policies_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_PatchAssociation_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_Get_sync", "segments": [ { "end": 53, @@ -55497,28 +57269,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_patch_association_sync.py" + "title": "compute_v1beta_generated_region_network_policies_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.patch_rule", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.insert", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.PatchRule", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.Insert", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "PatchRule" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.PatchRuleRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.InsertRegionNetworkPolicyRequest" }, { "name": "project", @@ -55529,12 +57301,8 @@ "type": "str" }, { - "name": "firewall_policy", - "type": "str" - }, - { - "name": "firewall_policy_rule_resource", - "type": "google.cloud.compute_v1beta.types.FirewallPolicyRule" + "name": "network_policy_resource", + "type": "google.cloud.compute_v1beta.types.NetworkPolicy" }, { "name": "retry", @@ -55550,21 +57318,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch_rule" + "shortName": "insert" }, - "description": "Sample for PatchRule", - "file": "compute_v1beta_generated_region_network_firewall_policies_patch_rule_sync.py", + "description": "Sample for Insert", + "file": "compute_v1beta_generated_region_network_policies_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_PatchRule_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -55574,43 +57342,43 @@ "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_v1beta_generated_region_network_firewall_policies_patch_rule_sync.py" + "title": "compute_v1beta_generated_region_network_policies_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.patch", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.Patch", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.List", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "Patch" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.PatchRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.ListRegionNetworkPoliciesRequest" }, { "name": "project", @@ -55620,14 +57388,6 @@ "name": "region", "type": "str" }, - { - "name": "firewall_policy", - "type": "str" - }, - { - "name": "firewall_policy_resource", - "type": "google.cloud.compute_v1beta.types.FirewallPolicy" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -55641,14 +57401,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1beta.services.region_network_policies.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Patch", - "file": "compute_v1beta_generated_region_network_firewall_policies_patch_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_region_network_policies_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_Patch_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_List_sync", "segments": [ { "end": 53, @@ -55666,43 +57426,43 @@ "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_v1beta_generated_region_network_firewall_policies_patch_sync.py" + "title": "compute_v1beta_generated_region_network_policies_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.remove_association", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.patch_traffic_classification_rule", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.RemoveAssociation", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.PatchTrafficClassificationRule", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "RemoveAssociation" + "shortName": "PatchTrafficClassificationRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.RemoveAssociationRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.PatchTrafficClassificationRuleRegionNetworkPolicyRequest" }, { "name": "project", @@ -55713,9 +57473,13 @@ "type": "str" }, { - "name": "firewall_policy", + "name": "network_policy", "type": "str" }, + { + "name": "network_policy_traffic_classification_rule_resource", + "type": "google.cloud.compute_v1beta.types.NetworkPolicyTrafficClassificationRule" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -55730,13 +57494,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "remove_association" + "shortName": "patch_traffic_classification_rule" }, - "description": "Sample for RemoveAssociation", - "file": "compute_v1beta_generated_region_network_firewall_policies_remove_association_sync.py", + "description": "Sample for PatchTrafficClassificationRule", + "file": "compute_v1beta_generated_region_network_policies_patch_traffic_classification_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_RemoveAssociation_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_PatchTrafficClassificationRule_sync", "segments": [ { "end": 53, @@ -55769,28 +57533,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_remove_association_sync.py" + "title": "compute_v1beta_generated_region_network_policies_patch_traffic_classification_rule_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.remove_rule", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.patch", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.RemoveRule", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.Patch", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "RemoveRule" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.RemoveRuleRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.PatchRegionNetworkPolicyRequest" }, { "name": "project", @@ -55801,9 +57565,13 @@ "type": "str" }, { - "name": "firewall_policy", + "name": "network_policy", "type": "str" }, + { + "name": "network_policy_resource", + "type": "google.cloud.compute_v1beta.types.NetworkPolicy" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -55818,13 +57586,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "remove_rule" + "shortName": "patch" }, - "description": "Sample for RemoveRule", - "file": "compute_v1beta_generated_region_network_firewall_policies_remove_rule_sync.py", + "description": "Sample for Patch", + "file": "compute_v1beta_generated_region_network_policies_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_RemoveRule_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_Patch_sync", "segments": [ { "end": 53, @@ -55857,28 +57625,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_remove_rule_sync.py" + "title": "compute_v1beta_generated_region_network_policies_patch_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.set_iam_policy", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.remove_association", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.SetIamPolicy", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.RemoveAssociation", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "SetIamPolicy" + "shortName": "RemoveAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.SetIamPolicyRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.RemoveAssociationRegionNetworkPolicyRequest" }, { "name": "project", @@ -55889,13 +57657,9 @@ "type": "str" }, { - "name": "resource", + "name": "network_policy", "type": "str" }, - { - "name": "region_set_policy_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionSetPolicyRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -55909,14 +57673,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "remove_association" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1beta_generated_region_network_firewall_policies_set_iam_policy_sync.py", + "description": "Sample for RemoveAssociation", + "file": "compute_v1beta_generated_region_network_policies_remove_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_SetIamPolicy_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_RemoveAssociation_sync", "segments": [ { "end": 53, @@ -55949,28 +57713,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_set_iam_policy_sync.py" + "title": "compute_v1beta_generated_region_network_policies_remove_association_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient", - "shortName": "RegionNetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient", + "shortName": "RegionNetworkPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionNetworkFirewallPoliciesClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1beta.RegionNetworkPoliciesClient.remove_traffic_classification_rule", "method": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies.TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies.RemoveTrafficClassificationRule", "service": { - "fullName": "google.cloud.compute.v1beta.RegionNetworkFirewallPolicies", - "shortName": "RegionNetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1beta.RegionNetworkPolicies", + "shortName": "RegionNetworkPolicies" }, - "shortName": "TestIamPermissions" + "shortName": "RemoveTrafficClassificationRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.TestIamPermissionsRegionNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1beta.types.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest" }, { "name": "project", @@ -55981,13 +57745,9 @@ "type": "str" }, { - "name": "resource", + "name": "network_policy", "type": "str" }, - { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1beta.types.TestPermissionsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -56001,14 +57761,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "remove_traffic_classification_rule" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1beta_generated_region_network_firewall_policies_test_iam_permissions_sync.py", + "description": "Sample for RemoveTrafficClassificationRule", + "file": "compute_v1beta_generated_region_network_policies_remove_traffic_classification_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionNetworkFirewallPolicies_TestIamPermissions_sync", + "regionTag": "compute_v1beta_generated_RegionNetworkPolicies_RemoveTrafficClassificationRule_sync", "segments": [ { "end": 53, @@ -56041,7 +57801,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_network_firewall_policies_test_iam_permissions_sync.py" + "title": "compute_v1beta_generated_region_network_policies_remove_traffic_classification_rule_sync.py" }, { "canonical": true, @@ -62955,6 +64715,102 @@ ], "title": "compute_v1beta_generated_reservation_sub_blocks_perform_maintenance_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ReservationSubBlocksClient", + "shortName": "ReservationSubBlocksClient" + }, + "fullName": "google.cloud.compute_v1beta.ReservationSubBlocksClient.report_faulty", + "method": { + "fullName": "google.cloud.compute.v1beta.ReservationSubBlocks.ReportFaulty", + "service": { + "fullName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "shortName": "ReservationSubBlocks" + }, + "shortName": "ReportFaulty" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ReportFaultyReservationSubBlockRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "parent_name", + "type": "str" + }, + { + "name": "reservation_sub_block", + "type": "str" + }, + { + "name": "reservation_sub_blocks_report_faulty_request_resource", + "type": "google.cloud.compute_v1beta.types.ReservationSubBlocksReportFaultyRequest" + }, + { + "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": "report_faulty" + }, + "description": "Sample for ReportFaulty", + "file": "compute_v1beta_generated_reservation_sub_blocks_report_faulty_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_ReservationSubBlocks_ReportFaulty_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_reservation_sub_blocks_report_faulty_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute-v1beta/scripts/fixup_compute_v1beta_keywords.py b/packages/google-cloud-compute-v1beta/scripts/fixup_compute_v1beta_keywords.py index 727d9580cad3..f178ce5a4a82 100644 --- a/packages/google-cloud-compute-v1beta/scripts/fixup_compute_v1beta_keywords.py +++ b/packages/google-cloud-compute-v1beta/scripts/fixup_compute_v1beta_keywords.py @@ -52,6 +52,7 @@ class computeCallTransformer(cst.CSTTransformer): 'add_resource_policies': ('disk', 'disks_add_resource_policies_request_resource', 'project', 'zone', 'request_id', ), 'add_rule': ('firewall_policy', 'firewall_policy_rule_resource', 'request_id', ), 'add_signed_url_key': ('backend_bucket', 'project', 'signed_url_key_resource', 'request_id', ), + 'add_traffic_classification_rule': ('network_policy', 'network_policy_traffic_classification_rule_resource', 'project', 'region', 'request_id', ), 'aggregated_list': ('project', 'filter', 'include_all_scopes', 'max_results', 'order_by', 'page_token', 'return_partial_success', 'service_project_number', ), 'announce': ('project', 'public_advertised_prefix', 'request_id', ), 'apply_updates_to_instances': ('instance_group_manager', 'instance_group_managers_apply_updates_request_resource', 'project', 'zone', ), @@ -105,6 +106,7 @@ class computeCallTransformer(cst.CSTTransformer): 'get_shielded_instance_identity': ('instance', 'project', 'zone', ), 'get_shielded_vm_identity': ('instance', 'project', 'zone', ), 'get_status': ('project', 'region', 'vpn_gateway', ), + 'get_traffic_classification_rule': ('network_policy', 'project', 'region', 'priority', ), 'get_xpn_host': ('project', ), 'get_xpn_resources': ('project', 'filter', 'max_results', 'order_by', 'page_token', 'return_partial_success', ), 'insert': ('address_resource', 'project', 'region', 'request_id', ), @@ -136,6 +138,7 @@ class computeCallTransformer(cst.CSTTransformer): 'patch_per_instance_configs': ('instance_group_manager', 'instance_group_managers_patch_per_instance_configs_req_resource', 'project', 'zone', 'request_id', ), 'patch_route_policy': ('project', 'region', 'route_policy_resource', 'router', 'request_id', ), 'patch_rule': ('firewall_policy', 'firewall_policy_rule_resource', 'priority', 'request_id', ), + 'patch_traffic_classification_rule': ('network_policy', 'network_policy_traffic_classification_rule_resource', 'project', 'region', 'priority', 'request_id', ), 'perform_maintenance': ('instance', 'project', 'zone', 'request_id', ), 'preview': ('project', 'region', 'router', 'router_resource', ), 'recreate_instances': ('instance_group_manager', 'instance_group_managers_recreate_instances_request_resource', 'project', 'zone', 'request_id', ), @@ -147,6 +150,8 @@ class computeCallTransformer(cst.CSTTransformer): 'remove_peering': ('network', 'networks_remove_peering_request_resource', 'project', 'request_id', ), 'remove_resource_policies': ('disk', 'disks_remove_resource_policies_request_resource', 'project', 'zone', 'request_id', ), 'remove_rule': ('firewall_policy', 'priority', 'request_id', ), + 'remove_traffic_classification_rule': ('network_policy', 'project', 'region', 'priority', 'request_id', ), + 'report_faulty': ('parent_name', 'project', 'reservation_sub_block', 'reservation_sub_blocks_report_faulty_request_resource', 'zone', 'request_id', ), 'report_host_as_faulty': ('instance', 'instances_report_host_as_faulty_request_resource', 'project', 'zone', 'request_id', ), 'request_remove_peering': ('network', 'networks_request_remove_peering_request_resource', 'project', 'request_id', ), 'reset': ('instance', 'project', 'zone', 'request_id', ), diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_addresses.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_addresses.py index 4c6ee0047993..8b12baf48f49 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_addresses.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_addresses.py @@ -3985,6 +3985,7 @@ def test_get_rest_call_success(request_type): creation_timestamp="creation_timestamp_value", description="description_value", id=205, + ip_collection="ip_collection_value", ip_version="ip_version_value", ipv6_endpoint_type="ipv6_endpoint_type_value", kind="kind_value", @@ -4020,6 +4021,7 @@ def test_get_rest_call_success(request_type): assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.id == 205 + assert response.ip_collection == "ip_collection_value" assert response.ip_version == "ip_version_value" assert response.ipv6_endpoint_type == "ipv6_endpoint_type_value" assert response.kind == "kind_value" @@ -4137,6 +4139,7 @@ def test_insert_rest_call_success(request_type): "creation_timestamp": "creation_timestamp_value", "description": "description_value", "id": 205, + "ip_collection": "ip_collection_value", "ip_version": "ip_version_value", "ipv6_endpoint_type": "ipv6_endpoint_type_value", "kind": "kind_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_disks.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_disks.py index 7e8d89567c8e..3cca91386865 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_disks.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_disks.py @@ -8844,6 +8844,7 @@ def test_create_snapshot_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "location_hint": "location_hint_value", "name": "name_value", + "params": {"resource_manager_tags": {}}, "region": "region_value", "satisfies_pzi": True, "satisfies_pzs": True, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_addresses.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_addresses.py index 5ec6d1b3a55e..e212807dc539 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_addresses.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_addresses.py @@ -3513,6 +3513,7 @@ def test_get_rest_call_success(request_type): creation_timestamp="creation_timestamp_value", description="description_value", id=205, + ip_collection="ip_collection_value", ip_version="ip_version_value", ipv6_endpoint_type="ipv6_endpoint_type_value", kind="kind_value", @@ -3548,6 +3549,7 @@ def test_get_rest_call_success(request_type): assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.id == 205 + assert response.ip_collection == "ip_collection_value" assert response.ip_version == "ip_version_value" assert response.ipv6_endpoint_type == "ipv6_endpoint_type_value" assert response.kind == "kind_value" @@ -3669,6 +3671,7 @@ def test_insert_rest_call_success(request_type): "creation_timestamp": "creation_timestamp_value", "description": "description_value", "id": 205, + "ip_collection": "ip_collection_value", "ip_version": "ip_version_value", "ipv6_endpoint_type": "ipv6_endpoint_type_value", "kind": "kind_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_public_delegated_prefixes.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_public_delegated_prefixes.py index b6ad3285ac57..5a6fe1ca73c6 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_public_delegated_prefixes.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_public_delegated_prefixes.py @@ -2977,6 +2977,7 @@ def test_get_rest_call_success(request_type): byoip_api_version="byoip_api_version_value", creation_timestamp="creation_timestamp_value", description="description_value", + enable_enhanced_ipv4_allocation=True, fingerprint="fingerprint_value", id=205, ip_cidr_range="ip_cidr_range_value", @@ -3008,6 +3009,7 @@ def test_get_rest_call_success(request_type): assert response.byoip_api_version == "byoip_api_version_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" + assert response.enable_enhanced_ipv4_allocation is True assert response.fingerprint == "fingerprint_value" assert response.id == 205 assert response.ip_cidr_range == "ip_cidr_range_value" @@ -3130,6 +3132,7 @@ def test_insert_rest_call_success(request_type): "byoip_api_version": "byoip_api_version_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", + "enable_enhanced_ipv4_allocation": True, "fingerprint": "fingerprint_value", "id": 205, "ip_cidr_range": "ip_cidr_range_value", @@ -3143,6 +3146,7 @@ def test_insert_rest_call_success(request_type): "allocatable_prefix_length": 2626, "delegatee_project": "delegatee_project_value", "description": "description_value", + "enable_enhanced_ipv4_allocation": True, "ip_cidr_range": "ip_cidr_range_value", "is_address": True, "mode": "mode_value", @@ -3541,6 +3545,7 @@ def test_patch_rest_call_success(request_type): "byoip_api_version": "byoip_api_version_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", + "enable_enhanced_ipv4_allocation": True, "fingerprint": "fingerprint_value", "id": 205, "ip_cidr_range": "ip_cidr_range_value", @@ -3554,6 +3559,7 @@ def test_patch_rest_call_success(request_type): "allocatable_prefix_length": 2626, "delegatee_project": "delegatee_project_value", "description": "description_value", + "enable_enhanced_ipv4_allocation": True, "ip_cidr_range": "ip_cidr_range_value", "is_address": True, "mode": "mode_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_images.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_images.py index 80d4a42a0bc5..81ad39e955fa 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_images.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_images.py @@ -5198,6 +5198,7 @@ def test_insert_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "locked": True, "name": "name_value", + "params": {"resource_manager_tags": {}}, "raw_disk": { "container_type": "container_type_value", "sha1_checksum": "sha1_checksum_value", @@ -5619,6 +5620,7 @@ def test_patch_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "locked": True, "name": "name_value", + "params": {"resource_manager_tags": {}}, "raw_disk": { "container_type": "container_type_value", "sha1_checksum": "sha1_checksum_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py index e71ef67d1553..d128a8b15c8e 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py @@ -3898,6 +3898,7 @@ def test_get_rest_call_success(request_type): satisfies_pzs=True, self_link="self_link_value", state="state_value", + subzone="subzone_value", wire_groups=["wire_groups_value"], ) @@ -3943,6 +3944,7 @@ def test_get_rest_call_success(request_type): assert response.satisfies_pzs is True assert response.self_link == "self_link_value" assert response.state == "state_value" + assert response.subzone == "subzone_value" assert response.wire_groups == ["wire_groups_value"] @@ -4384,6 +4386,7 @@ def test_insert_rest_call_success(request_type): "satisfies_pzs": True, "self_link": "self_link_value", "state": "state_value", + "subzone": "subzone_value", "wire_groups": ["wire_groups_value1", "wire_groups_value2"], } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -4833,6 +4836,7 @@ def test_patch_rest_call_success(request_type): "satisfies_pzs": True, "self_link": "self_link_value", "state": "state_value", + "subzone": "subzone_value", "wire_groups": ["wire_groups_value1", "wire_groups_value2"], } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_public_delegated_prefixes.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_public_delegated_prefixes.py index b9479efaac98..c9743fbdc72a 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_public_delegated_prefixes.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_public_delegated_prefixes.py @@ -4482,6 +4482,7 @@ def test_get_rest_call_success(request_type): byoip_api_version="byoip_api_version_value", creation_timestamp="creation_timestamp_value", description="description_value", + enable_enhanced_ipv4_allocation=True, fingerprint="fingerprint_value", id=205, ip_cidr_range="ip_cidr_range_value", @@ -4513,6 +4514,7 @@ def test_get_rest_call_success(request_type): assert response.byoip_api_version == "byoip_api_version_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" + assert response.enable_enhanced_ipv4_allocation is True assert response.fingerprint == "fingerprint_value" assert response.id == 205 assert response.ip_cidr_range == "ip_cidr_range_value" @@ -4634,6 +4636,7 @@ def test_insert_rest_call_success(request_type): "byoip_api_version": "byoip_api_version_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", + "enable_enhanced_ipv4_allocation": True, "fingerprint": "fingerprint_value", "id": 205, "ip_cidr_range": "ip_cidr_range_value", @@ -4647,6 +4650,7 @@ def test_insert_rest_call_success(request_type): "allocatable_prefix_length": 2626, "delegatee_project": "delegatee_project_value", "description": "description_value", + "enable_enhanced_ipv4_allocation": True, "ip_cidr_range": "ip_cidr_range_value", "is_address": True, "mode": "mode_value", @@ -5049,6 +5053,7 @@ def test_patch_rest_call_success(request_type): "byoip_api_version": "byoip_api_version_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", + "enable_enhanced_ipv4_allocation": True, "fingerprint": "fingerprint_value", "id": 205, "ip_cidr_range": "ip_cidr_range_value", @@ -5062,6 +5067,7 @@ def test_patch_rest_call_success(request_type): "allocatable_prefix_length": 2626, "delegatee_project": "delegatee_project_value", "description": "description_value", + "enable_enhanced_ipv4_allocation": True, "ip_cidr_range": "ip_cidr_range_value", "is_address": True, "mode": "mode_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_disks.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_disks.py index 7543ac7a1d4c..5a6d74241309 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_disks.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_disks.py @@ -7779,6 +7779,7 @@ def test_create_snapshot_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "location_hint": "location_hint_value", "name": "name_value", + "params": {"resource_manager_tags": {}}, "region": "region_value", "satisfies_pzi": True, "satisfies_pzs": True, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_health_sources.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_health_sources.py new file mode 100644 index 000000000000..2c8d8fe92287 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_health_sources.py @@ -0,0 +1,5144 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +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 + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation # type: ignore +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.region_health_sources import ( + RegionHealthSourcesClient, + pagers, + transports, +) +from google.cloud.compute_v1beta.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" + + assert RegionHealthSourcesClient._get_default_mtls_endpoint(None) is None + assert ( + RegionHealthSourcesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionHealthSourcesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionHealthSourcesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionHealthSourcesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionHealthSourcesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert RegionHealthSourcesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionHealthSourcesClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionHealthSourcesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + RegionHealthSourcesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RegionHealthSourcesClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionHealthSourcesClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionHealthSourcesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionHealthSourcesClient._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 RegionHealthSourcesClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RegionHealthSourcesClient._get_client_cert_source(None, False) is None + assert ( + RegionHealthSourcesClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + RegionHealthSourcesClient._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 ( + RegionHealthSourcesClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RegionHealthSourcesClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + RegionHealthSourcesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionHealthSourcesClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionHealthSourcesClient._DEFAULT_UNIVERSE + default_endpoint = RegionHealthSourcesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RegionHealthSourcesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + RegionHealthSourcesClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RegionHealthSourcesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RegionHealthSourcesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionHealthSourcesClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + RegionHealthSourcesClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == RegionHealthSourcesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionHealthSourcesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RegionHealthSourcesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionHealthSourcesClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + RegionHealthSourcesClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionHealthSourcesClient._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 ( + RegionHealthSourcesClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + RegionHealthSourcesClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RegionHealthSourcesClient._get_universe_domain(None, None) + == RegionHealthSourcesClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + RegionHealthSourcesClient._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 = RegionHealthSourcesClient(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 = RegionHealthSourcesClient(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", + [ + (RegionHealthSourcesClient, "rest"), + ], +) +def test_region_health_sources_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.RegionHealthSourcesRestTransport, "rest"), + ], +) +def test_region_health_sources_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", + [ + (RegionHealthSourcesClient, "rest"), + ], +) +def test_region_health_sources_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_region_health_sources_client_get_transport_class(): + transport = RegionHealthSourcesClient.get_transport_class() + available_transports = [ + transports.RegionHealthSourcesRestTransport, + ] + assert transport in available_transports + + transport = RegionHealthSourcesClient.get_transport_class("rest") + assert transport == transports.RegionHealthSourcesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionHealthSourcesClient, + transports.RegionHealthSourcesRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + RegionHealthSourcesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionHealthSourcesClient), +) +def test_region_health_sources_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(RegionHealthSourcesClient, "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(RegionHealthSourcesClient, "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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # 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", + [ + ( + RegionHealthSourcesClient, + transports.RegionHealthSourcesRestTransport, + "rest", + "true", + ), + ( + RegionHealthSourcesClient, + transports.RegionHealthSourcesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + RegionHealthSourcesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionHealthSourcesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_region_health_sources_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", [RegionHealthSourcesClient]) +@mock.patch.object( + RegionHealthSourcesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionHealthSourcesClient), +) +def test_region_health_sources_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_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`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [RegionHealthSourcesClient]) +@mock.patch.object( + RegionHealthSourcesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionHealthSourcesClient), +) +def test_region_health_sources_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionHealthSourcesClient._DEFAULT_UNIVERSE + default_endpoint = RegionHealthSourcesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RegionHealthSourcesClient._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", + [ + ( + RegionHealthSourcesClient, + transports.RegionHealthSourcesRestTransport, + "rest", + ), + ], +) +def test_region_health_sources_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", + [ + ( + RegionHealthSourcesClient, + transports.RegionHealthSourcesRestTransport, + "rest", + None, + ), + ], +) +def test_region_health_sources_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 = RegionHealthSourcesClient( + 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.AggregatedListRegionHealthSourcesRequest, +): + transport_class = transports.RegionHealthSourcesRestTransport + + 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 = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.HealthSourceAggregatedList() + # 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.HealthSourceAggregatedList.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 expected_params == actual_params + + +def test_aggregated_list_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + 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 = RegionHealthSourcesClient( + 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.HealthSourceAggregatedList() + + # 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.HealthSourceAggregatedList.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/beta/projects/{project}/aggregated/healthSources" + % client.transport._host, + args[1], + ) + + +def test_aggregated_list_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.AggregatedListRegionHealthSourcesRequest(), + project="project_value", + ) + + +def test_aggregated_list_rest_pager(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.HealthSourceAggregatedList( + items={ + "a": compute.HealthSourcesScopedList(), + "b": compute.HealthSourcesScopedList(), + "c": compute.HealthSourcesScopedList(), + }, + next_page_token="abc", + ), + compute.HealthSourceAggregatedList( + items={}, + next_page_token="def", + ), + compute.HealthSourceAggregatedList( + items={ + "g": compute.HealthSourcesScopedList(), + }, + next_page_token="ghi", + ), + compute.HealthSourceAggregatedList( + items={ + "h": compute.HealthSourcesScopedList(), + "i": compute.HealthSourcesScopedList(), + }, + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.HealthSourceAggregatedList.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.HealthSourcesScopedList) + 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.HealthSourcesScopedList, + ) + + assert pager.get("a") is None + assert isinstance(pager.get("h"), compute.HealthSourcesScopedList) + + 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 = RegionHealthSourcesClient( + 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.DeleteRegionHealthSourceRequest, +): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["health_source"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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["healthSource"] = "health_source_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "healthSource" in jsonified_request + assert jsonified_request["healthSource"] == "health_source_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionHealthSourcesClient( + 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 expected_params == actual_params + + +def test_delete_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "healthSource", + "project", + "region", + ) + ) + ) + + +def test_delete_rest_flattened(): + client = RegionHealthSourcesClient( + 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", + "region": "sample2", + "health_source": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + health_source="health_source_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/beta/projects/{project}/regions/{region}/healthSources/{health_source}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.DeleteRegionHealthSourceRequest(), + project="project_value", + region="region_value", + health_source="health_source_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 = RegionHealthSourcesClient( + 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.DeleteRegionHealthSourceRequest, +): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["health_source"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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["healthSource"] = "health_source_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "healthSource" in jsonified_request + assert jsonified_request["healthSource"] == "health_source_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionHealthSourcesClient( + 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 expected_params == actual_params + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "healthSource", + "project", + "region", + ) + ) + ) + + +def test_delete_unary_rest_flattened(): + client = RegionHealthSourcesClient( + 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", + "region": "sample2", + "health_source": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + health_source="health_source_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/beta/projects/{project}/regions/{region}/healthSources/{health_source}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.DeleteRegionHealthSourceRequest(), + project="project_value", + region="region_value", + health_source="health_source_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 = RegionHealthSourcesClient( + 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.GetRegionHealthSourceRequest): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["health_source"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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["healthSource"] = "health_source_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "healthSource" in jsonified_request + assert jsonified_request["healthSource"] == "health_source_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.HealthSource() + # 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.HealthSource.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 expected_params == actual_params + + +def test_get_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "healthSource", + "project", + "region", + ) + ) + ) + + +def test_get_rest_flattened(): + client = RegionHealthSourcesClient( + 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.HealthSource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "health_source": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + health_source="health_source_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.HealthSource.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/beta/projects/{project}/regions/{region}/healthSources/{health_source}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.GetRegionHealthSourceRequest(), + project="project_value", + region="region_value", + health_source="health_source_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 = RegionHealthSourcesClient( + 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.InsertRegionHealthSourceRequest, +): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + 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" + jsonified_request["region"] = "region_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" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionHealthSourcesClient( + 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 expected_params == actual_params + + +def test_insert_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "healthSourceResource", + "project", + "region", + ) + ) + ) + + +def test_insert_rest_flattened(): + client = RegionHealthSourcesClient( + 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", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + health_source_resource=compute.HealthSource( + 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/beta/projects/{project}/regions/{region}/healthSources" + % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.InsertRegionHealthSourceRequest(), + project="project_value", + region="region_value", + health_source_resource=compute.HealthSource( + 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 = RegionHealthSourcesClient( + 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.InsertRegionHealthSourceRequest, +): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + 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" + jsonified_request["region"] = "region_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" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionHealthSourcesClient( + 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 expected_params == actual_params + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "healthSourceResource", + "project", + "region", + ) + ) + ) + + +def test_insert_unary_rest_flattened(): + client = RegionHealthSourcesClient( + 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", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + health_source_resource=compute.HealthSource( + 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/beta/projects/{project}/regions/{region}/healthSources" + % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.InsertRegionHealthSourceRequest(), + project="project_value", + region="region_value", + health_source_resource=compute.HealthSource( + 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 = RegionHealthSourcesClient( + 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.ListRegionHealthSourcesRequest): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + 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" + jsonified_request["region"] = "region_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" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.HealthSourceList() + # 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.HealthSourceList.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 expected_params == actual_params + + +def test_list_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set( + ( + "project", + "region", + ) + ) + ) + + +def test_list_rest_flattened(): + client = RegionHealthSourcesClient( + 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.HealthSourceList() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_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.HealthSourceList.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/beta/projects/{project}/regions/{region}/healthSources" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.ListRegionHealthSourcesRequest(), + project="project_value", + region="region_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.HealthSourceList( + items=[ + compute.HealthSource(), + compute.HealthSource(), + compute.HealthSource(), + ], + next_page_token="abc", + ), + compute.HealthSourceList( + items=[], + next_page_token="def", + ), + compute.HealthSourceList( + items=[ + compute.HealthSource(), + ], + next_page_token="ghi", + ), + compute.HealthSourceList( + items=[ + compute.HealthSource(), + compute.HealthSource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.HealthSourceList.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", "region": "sample2"} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.HealthSource) 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_patch_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 = RegionHealthSourcesClient( + 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.patch 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.patch] = mock_rpc + + request = {} + client.patch(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.patch(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_patch_rest_required_fields( + request_type=compute.PatchRegionHealthSourceRequest, +): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["health_source"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).patch._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["healthSource"] = "health_source_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch._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 "healthSource" in jsonified_request + assert jsonified_request["healthSource"] == "health_source_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionHealthSourcesClient( + 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.patch(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "healthSource", + "healthSourceResource", + "project", + "region", + ) + ) + ) + + +def test_patch_rest_flattened(): + client = RegionHealthSourcesClient( + 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", + "region": "sample2", + "health_source": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + health_source="health_source_value", + health_source_resource=compute.HealthSource( + 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.patch(**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/beta/projects/{project}/regions/{region}/healthSources/{health_source}" + % client.transport._host, + args[1], + ) + + +def test_patch_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.patch( + compute.PatchRegionHealthSourceRequest(), + project="project_value", + region="region_value", + health_source="health_source_value", + health_source_resource=compute.HealthSource( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_patch_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 = RegionHealthSourcesClient( + 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.patch 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.patch] = mock_rpc + + request = {} + client.patch_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.patch_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_patch_unary_rest_required_fields( + request_type=compute.PatchRegionHealthSourceRequest, +): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["health_source"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).patch._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["healthSource"] = "health_source_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch._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 "healthSource" in jsonified_request + assert jsonified_request["healthSource"] == "health_source_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionHealthSourcesClient( + 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.patch_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_unary_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "healthSource", + "healthSourceResource", + "project", + "region", + ) + ) + ) + + +def test_patch_unary_rest_flattened(): + client = RegionHealthSourcesClient( + 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", + "region": "sample2", + "health_source": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + health_source="health_source_value", + health_source_resource=compute.HealthSource( + 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.patch_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/beta/projects/{project}/regions/{region}/healthSources/{health_source}" + % client.transport._host, + args[1], + ) + + +def test_patch_unary_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.patch_unary( + compute.PatchRegionHealthSourceRequest(), + project="project_value", + region="region_value", + health_source="health_source_value", + health_source_resource=compute.HealthSource( + creation_timestamp="creation_timestamp_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 + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RegionHealthSourcesClient( + 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.test_iam_permissions 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.test_iam_permissions + ] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(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_test_iam_permissions_rest_required_fields( + request_type=compute.TestIamPermissionsRegionHealthSourceRequest, +): + transport_class = transports.RegionHealthSourcesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + 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() + ).test_iam_permissions._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["region"] = "region_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._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 "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse() + # 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.TestPermissionsResponse.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.test_iam_permissions(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "region", + "resource", + "testPermissionsRequestResource", + ) + ) + ) + + +def test_test_iam_permissions_rest_flattened(): + client = RegionHealthSourcesClient( + 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.TestPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource="resource_value", + test_permissions_request_resource=compute.TestPermissionsRequest( + permissions=["permissions_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.TestPermissionsResponse.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.test_iam_permissions(**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/beta/projects/{project}/regions/{region}/healthSources/{resource}/testIamPermissions" + % client.transport._host, + args[1], + ) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = RegionHealthSourcesClient( + 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.test_iam_permissions( + compute.TestIamPermissionsRegionHealthSourceRequest(), + project="project_value", + region="region_value", + resource="resource_value", + test_permissions_request_resource=compute.TestPermissionsRequest( + permissions=["permissions_value"] + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionHealthSourcesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionHealthSourcesClient( + 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 = RegionHealthSourcesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionHealthSourcesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionHealthSourcesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionHealthSourcesRestTransport, + ], +) +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 = RegionHealthSourcesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_aggregated_list_rest_bad_request( + request_type=compute.AggregatedListRegionHealthSourcesRequest, +): + client = RegionHealthSourcesClient( + 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.AggregatedListRegionHealthSourcesRequest, + dict, + ], +) +def test_aggregated_list_rest_call_success(request_type): + client = RegionHealthSourcesClient( + 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.HealthSourceAggregatedList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_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.HealthSourceAggregatedList.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.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_aggregated_list_rest_interceptors(null_interceptor): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionHealthSourcesRestInterceptor(), + ) + client = RegionHealthSourcesClient(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.RegionHealthSourcesRestInterceptor, "post_aggregated_list" + ) as post, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, + "post_aggregated_list_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "pre_aggregated_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AggregatedListRegionHealthSourcesRequest.pb( + compute.AggregatedListRegionHealthSourcesRequest() + ) + 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.HealthSourceAggregatedList.to_json( + compute.HealthSourceAggregatedList() + ) + req.return_value.content = return_value + + request = compute.AggregatedListRegionHealthSourcesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.HealthSourceAggregatedList() + post_with_metadata.return_value = compute.HealthSourceAggregatedList(), 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.DeleteRegionHealthSourceRequest): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "health_source": "sample3", + } + 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.DeleteRegionHealthSourceRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "health_source": "sample3", + } + 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.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionHealthSourcesRestInterceptor(), + ) + client = RegionHealthSourcesClient(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.RegionHealthSourcesRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "post_delete_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteRegionHealthSourceRequest.pb( + compute.DeleteRegionHealthSourceRequest() + ) + 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.DeleteRegionHealthSourceRequest() + 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.GetRegionHealthSourceRequest): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "health_source": "sample3", + } + 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.GetRegionHealthSourceRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "health_source": "sample3", + } + 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.HealthSource( + creation_timestamp="creation_timestamp_value", + description="description_value", + fingerprint="fingerprint_value", + health_aggregation_policy="health_aggregation_policy_value", + id=205, + kind="kind_value", + name="name_value", + region="region_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + source_type="source_type_value", + sources=["sources_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.HealthSource.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.HealthSource) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.fingerprint == "fingerprint_value" + assert response.health_aggregation_policy == "health_aggregation_policy_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.source_type == "source_type_value" + assert response.sources == ["sources_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionHealthSourcesRestInterceptor(), + ) + client = RegionHealthSourcesClient(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.RegionHealthSourcesRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRegionHealthSourceRequest.pb( + compute.GetRegionHealthSourceRequest() + ) + 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.HealthSource.to_json(compute.HealthSource()) + req.return_value.content = return_value + + request = compute.GetRegionHealthSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.HealthSource() + post_with_metadata.return_value = compute.HealthSource(), 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.InsertRegionHealthSourceRequest): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "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.insert(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertRegionHealthSourceRequest, + dict, + ], +) +def test_insert_rest_call_success(request_type): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["health_source_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "fingerprint": "fingerprint_value", + "health_aggregation_policy": "health_aggregation_policy_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "region": "region_value", + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "source_type": "source_type_value", + "sources": ["sources_value1", "sources_value2"], + } + # 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.InsertRegionHealthSourceRequest.meta.fields[ + "health_source_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[ + "health_source_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["health_source_resource"][field])): + del request_init["health_source_resource"][field][i][subfield] + else: + del request_init["health_source_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.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionHealthSourcesRestInterceptor(), + ) + client = RegionHealthSourcesClient(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.RegionHealthSourcesRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "post_insert_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.InsertRegionHealthSourceRequest.pb( + compute.InsertRegionHealthSourceRequest() + ) + 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.InsertRegionHealthSourceRequest() + 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.ListRegionHealthSourcesRequest): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "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.list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListRegionHealthSourcesRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "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.HealthSourceList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_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.HealthSourceList.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.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionHealthSourcesRestInterceptor(), + ) + client = RegionHealthSourcesClient(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.RegionHealthSourcesRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListRegionHealthSourcesRequest.pb( + compute.ListRegionHealthSourcesRequest() + ) + 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.HealthSourceList.to_json(compute.HealthSourceList()) + req.return_value.content = return_value + + request = compute.ListRegionHealthSourcesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.HealthSourceList() + post_with_metadata.return_value = compute.HealthSourceList(), 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_patch_rest_bad_request(request_type=compute.PatchRegionHealthSourceRequest): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "health_source": "sample3", + } + 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.patch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.PatchRegionHealthSourceRequest, + dict, + ], +) +def test_patch_rest_call_success(request_type): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "health_source": "sample3", + } + request_init["health_source_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "fingerprint": "fingerprint_value", + "health_aggregation_policy": "health_aggregation_policy_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "region": "region_value", + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "source_type": "source_type_value", + "sources": ["sources_value1", "sources_value2"], + } + # 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.PatchRegionHealthSourceRequest.meta.fields[ + "health_source_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[ + "health_source_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["health_source_resource"][field])): + del request_init["health_source_resource"][field][i][subfield] + else: + del request_init["health_source_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.patch(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_patch_rest_interceptors(null_interceptor): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionHealthSourcesRestInterceptor(), + ) + client = RegionHealthSourcesClient(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.RegionHealthSourcesRestInterceptor, "post_patch" + ) as post, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "post_patch_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "pre_patch" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.PatchRegionHealthSourceRequest.pb( + compute.PatchRegionHealthSourceRequest() + ) + 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.PatchRegionHealthSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.patch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + request_type=compute.TestIamPermissionsRegionHealthSourceRequest, +): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + 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.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.TestIamPermissionsRegionHealthSourceRequest, + dict, + ], +) +def test_test_iam_permissions_rest_call_success(request_type): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request_init["test_permissions_request_resource"] = { + "permissions": ["permissions_value1", "permissions_value2"] + } + # 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.TestIamPermissionsRegionHealthSourceRequest.meta.fields[ + "test_permissions_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[ + "test_permissions_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["test_permissions_request_resource"][field]) + ): + del request_init["test_permissions_request_resource"][field][i][ + subfield + ] + else: + del request_init["test_permissions_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.TestPermissionsResponse( + permissions=["permissions_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.TestPermissionsResponse.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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.TestPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.RegionHealthSourcesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionHealthSourcesRestInterceptor(), + ) + client = RegionHealthSourcesClient(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.RegionHealthSourcesRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, + "post_test_iam_permissions_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionHealthSourcesRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.TestIamPermissionsRegionHealthSourceRequest.pb( + compute.TestIamPermissionsRegionHealthSourceRequest() + ) + 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.TestPermissionsResponse.to_json( + compute.TestPermissionsResponse() + ) + req.return_value.content = return_value + + request = compute.TestIamPermissionsRegionHealthSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.TestPermissionsResponse() + post_with_metadata.return_value = compute.TestPermissionsResponse(), metadata + + client.test_iam_permissions( + 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 = RegionHealthSourcesClient( + 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 = RegionHealthSourcesClient( + 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.AggregatedListRegionHealthSourcesRequest() + + 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 = RegionHealthSourcesClient( + 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.DeleteRegionHealthSourceRequest() + + 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 = RegionHealthSourcesClient( + 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.GetRegionHealthSourceRequest() + + 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 = RegionHealthSourcesClient( + 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.InsertRegionHealthSourceRequest() + + 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 = RegionHealthSourcesClient( + 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.ListRegionHealthSourcesRequest() + + 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_patch_unary_empty_call_rest(): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.patch), "__call__") as call: + client.patch_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PatchRegionHealthSourceRequest() + + 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(): + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.TestIamPermissionsRegionHealthSourceRequest() + + assert args[0] == request_msg + + +def test_region_health_sources_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionHealthSourcesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_region_health_sources_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.region_health_sources.transports.RegionHealthSourcesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RegionHealthSourcesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "aggregated_list", + "delete", + "get", + "insert", + "list", + "patch", + "test_iam_permissions", + ) + 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_region_health_sources_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_v1beta.services.region_health_sources.transports.RegionHealthSourcesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionHealthSourcesTransport( + 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_region_health_sources_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_v1beta.services.region_health_sources.transports.RegionHealthSourcesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionHealthSourcesTransport() + adc.assert_called_once() + + +def test_region_health_sources_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) + RegionHealthSourcesClient() + 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_region_health_sources_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.RegionHealthSourcesRestTransport( + 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_region_health_sources_host_no_port(transport_name): + client = RegionHealthSourcesClient( + 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_region_health_sources_host_with_port(transport_name): + client = RegionHealthSourcesClient( + 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_region_health_sources_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionHealthSourcesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionHealthSourcesClient( + 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.patch._session + session2 = client2.transport.patch._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RegionHealthSourcesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegionHealthSourcesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionHealthSourcesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RegionHealthSourcesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegionHealthSourcesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionHealthSourcesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = RegionHealthSourcesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegionHealthSourcesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionHealthSourcesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RegionHealthSourcesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegionHealthSourcesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionHealthSourcesClient.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 = RegionHealthSourcesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegionHealthSourcesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionHealthSourcesClient.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.RegionHealthSourcesTransport, "_prep_wrapped_messages" + ) as prep: + client = RegionHealthSourcesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RegionHealthSourcesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RegionHealthSourcesClient.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 = RegionHealthSourcesClient( + 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 = RegionHealthSourcesClient( + 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", + [ + (RegionHealthSourcesClient, transports.RegionHealthSourcesRestTransport), + ], +) +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-v1beta/tests/unit/gapic/compute_v1beta/test_region_network_policies.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_network_policies.py new file mode 100644 index 000000000000..04a28aa5bdac --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_network_policies.py @@ -0,0 +1,9169 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +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 + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation # type: ignore +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.region_network_policies import ( + RegionNetworkPoliciesClient, + pagers, + transports, +) +from google.cloud.compute_v1beta.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" + + assert RegionNetworkPoliciesClient._get_default_mtls_endpoint(None) is None + assert ( + RegionNetworkPoliciesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionNetworkPoliciesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionNetworkPoliciesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionNetworkPoliciesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionNetworkPoliciesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert RegionNetworkPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionNetworkPoliciesClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionNetworkPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + RegionNetworkPoliciesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RegionNetworkPoliciesClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionNetworkPoliciesClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionNetworkPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionNetworkPoliciesClient._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 RegionNetworkPoliciesClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RegionNetworkPoliciesClient._get_client_cert_source(None, False) is None + assert ( + RegionNetworkPoliciesClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + RegionNetworkPoliciesClient._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 ( + RegionNetworkPoliciesClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RegionNetworkPoliciesClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + RegionNetworkPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionNetworkPoliciesClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionNetworkPoliciesClient._DEFAULT_UNIVERSE + default_endpoint = RegionNetworkPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RegionNetworkPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + RegionNetworkPoliciesClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RegionNetworkPoliciesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RegionNetworkPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionNetworkPoliciesClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + RegionNetworkPoliciesClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == RegionNetworkPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionNetworkPoliciesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RegionNetworkPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionNetworkPoliciesClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + RegionNetworkPoliciesClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionNetworkPoliciesClient._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 ( + RegionNetworkPoliciesClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + RegionNetworkPoliciesClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RegionNetworkPoliciesClient._get_universe_domain(None, None) + == RegionNetworkPoliciesClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + RegionNetworkPoliciesClient._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 = RegionNetworkPoliciesClient(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 = RegionNetworkPoliciesClient(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", + [ + (RegionNetworkPoliciesClient, "rest"), + ], +) +def test_region_network_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.RegionNetworkPoliciesRestTransport, "rest"), + ], +) +def test_region_network_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", + [ + (RegionNetworkPoliciesClient, "rest"), + ], +) +def test_region_network_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_region_network_policies_client_get_transport_class(): + transport = RegionNetworkPoliciesClient.get_transport_class() + available_transports = [ + transports.RegionNetworkPoliciesRestTransport, + ] + assert transport in available_transports + + transport = RegionNetworkPoliciesClient.get_transport_class("rest") + assert transport == transports.RegionNetworkPoliciesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionNetworkPoliciesClient, + transports.RegionNetworkPoliciesRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + RegionNetworkPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionNetworkPoliciesClient), +) +def test_region_network_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(RegionNetworkPoliciesClient, "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(RegionNetworkPoliciesClient, "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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # 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", + [ + ( + RegionNetworkPoliciesClient, + transports.RegionNetworkPoliciesRestTransport, + "rest", + "true", + ), + ( + RegionNetworkPoliciesClient, + transports.RegionNetworkPoliciesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + RegionNetworkPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionNetworkPoliciesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_region_network_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", [RegionNetworkPoliciesClient]) +@mock.patch.object( + RegionNetworkPoliciesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionNetworkPoliciesClient), +) +def test_region_network_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_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`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [RegionNetworkPoliciesClient]) +@mock.patch.object( + RegionNetworkPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionNetworkPoliciesClient), +) +def test_region_network_policies_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionNetworkPoliciesClient._DEFAULT_UNIVERSE + default_endpoint = RegionNetworkPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RegionNetworkPoliciesClient._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", + [ + ( + RegionNetworkPoliciesClient, + transports.RegionNetworkPoliciesRestTransport, + "rest", + ), + ], +) +def test_region_network_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", + [ + ( + RegionNetworkPoliciesClient, + transports.RegionNetworkPoliciesRestTransport, + "rest", + None, + ), + ], +) +def test_region_network_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_add_association_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 = RegionNetworkPoliciesClient( + 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.add_association 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.add_association] = mock_rpc + + request = {} + client.add_association(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.add_association(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_add_association_rest_required_fields( + request_type=compute.AddAssociationRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).add_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_association._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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.add_association(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_association_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicy", + "networkPolicyAssociationResource", + "project", + "region", + ) + ) + ) + + +def test_add_association_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_association_resource=compute.NetworkPolicyAssociation( + attachment_target="attachment_target_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.add_association(**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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/addAssociation" + % client.transport._host, + args[1], + ) + + +def test_add_association_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.add_association( + compute.AddAssociationRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_association_resource=compute.NetworkPolicyAssociation( + attachment_target="attachment_target_value" + ), + ) + + +def test_add_association_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 = RegionNetworkPoliciesClient( + 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.add_association 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.add_association] = mock_rpc + + request = {} + client.add_association_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.add_association_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_add_association_unary_rest_required_fields( + request_type=compute.AddAssociationRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).add_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_association._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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.add_association_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_association_unary_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicy", + "networkPolicyAssociationResource", + "project", + "region", + ) + ) + ) + + +def test_add_association_unary_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_association_resource=compute.NetworkPolicyAssociation( + attachment_target="attachment_target_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.add_association_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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/addAssociation" + % client.transport._host, + args[1], + ) + + +def test_add_association_unary_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.add_association_unary( + compute.AddAssociationRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_association_resource=compute.NetworkPolicyAssociation( + attachment_target="attachment_target_value" + ), + ) + + +def test_add_traffic_classification_rule_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 = RegionNetworkPoliciesClient( + 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.add_traffic_classification_rule + 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.add_traffic_classification_rule + ] = mock_rpc + + request = {} + client.add_traffic_classification_rule(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.add_traffic_classification_rule(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_add_traffic_classification_rule_rest_required_fields( + request_type=compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).add_traffic_classification_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_traffic_classification_rule._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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.add_traffic_classification_rule(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_traffic_classification_rule_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_traffic_classification_rule._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicy", + "networkPolicyTrafficClassificationRuleResource", + "project", + "region", + ) + ) + ) + + +def test_add_traffic_classification_rule_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_traffic_classification_rule_resource=compute.NetworkPolicyTrafficClassificationRule( + action=compute.NetworkPolicyTrafficClassificationRuleAction( + dscp_mode="dscp_mode_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.add_traffic_classification_rule(**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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/addTrafficClassificationRule" + % client.transport._host, + args[1], + ) + + +def test_add_traffic_classification_rule_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.add_traffic_classification_rule( + compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_traffic_classification_rule_resource=compute.NetworkPolicyTrafficClassificationRule( + action=compute.NetworkPolicyTrafficClassificationRuleAction( + dscp_mode="dscp_mode_value" + ) + ), + ) + + +def test_add_traffic_classification_rule_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 = RegionNetworkPoliciesClient( + 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.add_traffic_classification_rule + 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.add_traffic_classification_rule + ] = mock_rpc + + request = {} + client.add_traffic_classification_rule_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.add_traffic_classification_rule_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_add_traffic_classification_rule_unary_rest_required_fields( + request_type=compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).add_traffic_classification_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_traffic_classification_rule._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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.add_traffic_classification_rule_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_traffic_classification_rule_unary_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_traffic_classification_rule._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicy", + "networkPolicyTrafficClassificationRuleResource", + "project", + "region", + ) + ) + ) + + +def test_add_traffic_classification_rule_unary_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_traffic_classification_rule_resource=compute.NetworkPolicyTrafficClassificationRule( + action=compute.NetworkPolicyTrafficClassificationRuleAction( + dscp_mode="dscp_mode_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.add_traffic_classification_rule_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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/addTrafficClassificationRule" + % client.transport._host, + args[1], + ) + + +def test_add_traffic_classification_rule_unary_rest_flattened_error( + transport: str = "rest", +): + client = RegionNetworkPoliciesClient( + 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.add_traffic_classification_rule_unary( + compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_traffic_classification_rule_resource=compute.NetworkPolicyTrafficClassificationRule( + action=compute.NetworkPolicyTrafficClassificationRuleAction( + dscp_mode="dscp_mode_value" + ) + ), + ) + + +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 = RegionNetworkPoliciesClient( + 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.AggregatedListRegionNetworkPoliciesRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + 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 = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.NetworkPolicyAggregatedList() + # 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.NetworkPolicyAggregatedList.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 expected_params == actual_params + + +def test_aggregated_list_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + 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 = RegionNetworkPoliciesClient( + 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.NetworkPolicyAggregatedList() + + # 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.NetworkPolicyAggregatedList.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/beta/projects/{project}/aggregated/networkPolicies" + % client.transport._host, + args[1], + ) + + +def test_aggregated_list_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.AggregatedListRegionNetworkPoliciesRequest(), + project="project_value", + ) + + +def test_aggregated_list_rest_pager(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.NetworkPolicyAggregatedList( + items={ + "a": compute.NetworkPoliciesScopedList(), + "b": compute.NetworkPoliciesScopedList(), + "c": compute.NetworkPoliciesScopedList(), + }, + next_page_token="abc", + ), + compute.NetworkPolicyAggregatedList( + items={}, + next_page_token="def", + ), + compute.NetworkPolicyAggregatedList( + items={ + "g": compute.NetworkPoliciesScopedList(), + }, + next_page_token="ghi", + ), + compute.NetworkPolicyAggregatedList( + items={ + "h": compute.NetworkPoliciesScopedList(), + "i": compute.NetworkPoliciesScopedList(), + }, + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.NetworkPolicyAggregatedList.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.NetworkPoliciesScopedList) + 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.NetworkPoliciesScopedList, + ) + + assert pager.get("a") is None + assert isinstance(pager.get("h"), compute.NetworkPoliciesScopedList) + + 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 = RegionNetworkPoliciesClient( + 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.DeleteRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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 expected_params == actual_params + + +def test_delete_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_delete_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.DeleteRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_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 = RegionNetworkPoliciesClient( + 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.DeleteRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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 expected_params == actual_params + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_delete_unary_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.DeleteRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_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 = RegionNetworkPoliciesClient( + 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.GetRegionNetworkPolicyRequest): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.NetworkPolicy() + # 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.NetworkPolicy.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 expected_params == actual_params + + +def test_get_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_get_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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.NetworkPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.NetworkPolicy.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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.GetRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + ) + + +def test_get_association_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 = RegionNetworkPoliciesClient( + 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_association 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_association] = mock_rpc + + request = {} + client.get_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_association(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_association_rest_required_fields( + request_type=compute.GetAssociationRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("name",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.NetworkPolicyAssociation() + # 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.NetworkPolicyAssociation.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_association(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_association_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("name",)) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_get_association_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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.NetworkPolicyAssociation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.NetworkPolicyAssociation.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_association(**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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/getAssociation" + % client.transport._host, + args[1], + ) + + +def test_get_association_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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_association( + compute.GetAssociationRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + ) + + +def test_get_traffic_classification_rule_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 = RegionNetworkPoliciesClient( + 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_traffic_classification_rule + 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_traffic_classification_rule + ] = mock_rpc + + request = {} + client.get_traffic_classification_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_traffic_classification_rule(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_traffic_classification_rule_rest_required_fields( + request_type=compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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_traffic_classification_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_traffic_classification_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("priority",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.NetworkPolicyTrafficClassificationRule() + # 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.NetworkPolicyTrafficClassificationRule.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_traffic_classification_rule(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_traffic_classification_rule_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_traffic_classification_rule._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("priority",)) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_get_traffic_classification_rule_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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.NetworkPolicyTrafficClassificationRule() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.NetworkPolicyTrafficClassificationRule.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_traffic_classification_rule(**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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/getTrafficClassificationRule" + % client.transport._host, + args[1], + ) + + +def test_get_traffic_classification_rule_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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_traffic_classification_rule( + compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_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 = RegionNetworkPoliciesClient( + 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.InsertRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + 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" + jsonified_request["region"] = "region_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" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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 expected_params == actual_params + + +def test_insert_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicyResource", + "project", + "region", + ) + ) + ) + + +def test_insert_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy_resource=compute.NetworkPolicy( + associations=[ + compute.NetworkPolicyAssociation( + attachment_target="attachment_target_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/beta/projects/{project}/regions/{region}/networkPolicies" + % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.InsertRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy_resource=compute.NetworkPolicy( + associations=[ + compute.NetworkPolicyAssociation( + attachment_target="attachment_target_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 = RegionNetworkPoliciesClient( + 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.InsertRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + 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" + jsonified_request["region"] = "region_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" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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 expected_params == actual_params + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicyResource", + "project", + "region", + ) + ) + ) + + +def test_insert_unary_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy_resource=compute.NetworkPolicy( + associations=[ + compute.NetworkPolicyAssociation( + attachment_target="attachment_target_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/beta/projects/{project}/regions/{region}/networkPolicies" + % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.InsertRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy_resource=compute.NetworkPolicy( + associations=[ + compute.NetworkPolicyAssociation( + attachment_target="attachment_target_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 = RegionNetworkPoliciesClient( + 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.ListRegionNetworkPoliciesRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + 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" + jsonified_request["region"] = "region_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" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.NetworkPolicyList() + # 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.NetworkPolicyList.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 expected_params == actual_params + + +def test_list_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set( + ( + "project", + "region", + ) + ) + ) + + +def test_list_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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.NetworkPolicyList() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_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.NetworkPolicyList.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/beta/projects/{project}/regions/{region}/networkPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.ListRegionNetworkPoliciesRequest(), + project="project_value", + region="region_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.NetworkPolicyList( + items=[ + compute.NetworkPolicy(), + compute.NetworkPolicy(), + compute.NetworkPolicy(), + ], + next_page_token="abc", + ), + compute.NetworkPolicyList( + items=[], + next_page_token="def", + ), + compute.NetworkPolicyList( + items=[ + compute.NetworkPolicy(), + ], + next_page_token="ghi", + ), + compute.NetworkPolicyList( + items=[ + compute.NetworkPolicy(), + compute.NetworkPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.NetworkPolicyList.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", "region": "sample2"} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.NetworkPolicy) 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_patch_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 = RegionNetworkPoliciesClient( + 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.patch 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.patch] = mock_rpc + + request = {} + client.patch(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.patch(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_patch_rest_required_fields( + request_type=compute.PatchRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).patch._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch._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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.patch(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicy", + "networkPolicyResource", + "project", + "region", + ) + ) + ) + + +def test_patch_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_resource=compute.NetworkPolicy( + associations=[ + compute.NetworkPolicyAssociation( + attachment_target="attachment_target_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.patch(**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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}" + % client.transport._host, + args[1], + ) + + +def test_patch_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.patch( + compute.PatchRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_resource=compute.NetworkPolicy( + associations=[ + compute.NetworkPolicyAssociation( + attachment_target="attachment_target_value" + ) + ] + ), + ) + + +def test_patch_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 = RegionNetworkPoliciesClient( + 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.patch 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.patch] = mock_rpc + + request = {} + client.patch_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.patch_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_patch_unary_rest_required_fields( + request_type=compute.PatchRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).patch._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch._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 "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.patch_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_unary_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "networkPolicy", + "networkPolicyResource", + "project", + "region", + ) + ) + ) + + +def test_patch_unary_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_resource=compute.NetworkPolicy( + associations=[ + compute.NetworkPolicyAssociation( + attachment_target="attachment_target_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.patch_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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}" + % client.transport._host, + args[1], + ) + + +def test_patch_unary_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.patch_unary( + compute.PatchRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_resource=compute.NetworkPolicy( + associations=[ + compute.NetworkPolicyAssociation( + attachment_target="attachment_target_value" + ) + ] + ), + ) + + +def test_patch_traffic_classification_rule_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 = RegionNetworkPoliciesClient( + 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.patch_traffic_classification_rule + 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.patch_traffic_classification_rule + ] = mock_rpc + + request = {} + client.patch_traffic_classification_rule(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.patch_traffic_classification_rule(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_patch_traffic_classification_rule_rest_required_fields( + request_type=compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).patch_traffic_classification_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch_traffic_classification_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "priority", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.patch_traffic_classification_rule(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_traffic_classification_rule_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.patch_traffic_classification_rule._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "priority", + "requestId", + ) + ) + & set( + ( + "networkPolicy", + "networkPolicyTrafficClassificationRuleResource", + "project", + "region", + ) + ) + ) + + +def test_patch_traffic_classification_rule_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_traffic_classification_rule_resource=compute.NetworkPolicyTrafficClassificationRule( + action=compute.NetworkPolicyTrafficClassificationRuleAction( + dscp_mode="dscp_mode_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.patch_traffic_classification_rule(**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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/patchTrafficClassificationRule" + % client.transport._host, + args[1], + ) + + +def test_patch_traffic_classification_rule_rest_flattened_error( + transport: str = "rest", +): + client = RegionNetworkPoliciesClient( + 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.patch_traffic_classification_rule( + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_traffic_classification_rule_resource=compute.NetworkPolicyTrafficClassificationRule( + action=compute.NetworkPolicyTrafficClassificationRuleAction( + dscp_mode="dscp_mode_value" + ) + ), + ) + + +def test_patch_traffic_classification_rule_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 = RegionNetworkPoliciesClient( + 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.patch_traffic_classification_rule + 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.patch_traffic_classification_rule + ] = mock_rpc + + request = {} + client.patch_traffic_classification_rule_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.patch_traffic_classification_rule_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_patch_traffic_classification_rule_unary_rest_required_fields( + request_type=compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).patch_traffic_classification_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch_traffic_classification_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "priority", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.patch_traffic_classification_rule_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_traffic_classification_rule_unary_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.patch_traffic_classification_rule._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "priority", + "requestId", + ) + ) + & set( + ( + "networkPolicy", + "networkPolicyTrafficClassificationRuleResource", + "project", + "region", + ) + ) + ) + + +def test_patch_traffic_classification_rule_unary_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_traffic_classification_rule_resource=compute.NetworkPolicyTrafficClassificationRule( + action=compute.NetworkPolicyTrafficClassificationRuleAction( + dscp_mode="dscp_mode_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.patch_traffic_classification_rule_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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/patchTrafficClassificationRule" + % client.transport._host, + args[1], + ) + + +def test_patch_traffic_classification_rule_unary_rest_flattened_error( + transport: str = "rest", +): + client = RegionNetworkPoliciesClient( + 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.patch_traffic_classification_rule_unary( + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + network_policy_traffic_classification_rule_resource=compute.NetworkPolicyTrafficClassificationRule( + action=compute.NetworkPolicyTrafficClassificationRuleAction( + dscp_mode="dscp_mode_value" + ) + ), + ) + + +def test_remove_association_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 = RegionNetworkPoliciesClient( + 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.remove_association 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.remove_association + ] = mock_rpc + + request = {} + client.remove_association(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.remove_association(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_remove_association_rest_required_fields( + request_type=compute.RemoveAssociationRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).remove_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "name", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.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.remove_association(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_association_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "name", + "requestId", + ) + ) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_remove_association_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.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.remove_association(**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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/removeAssociation" + % client.transport._host, + args[1], + ) + + +def test_remove_association_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.remove_association( + compute.RemoveAssociationRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + ) + + +def test_remove_association_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 = RegionNetworkPoliciesClient( + 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.remove_association 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.remove_association + ] = mock_rpc + + request = {} + client.remove_association_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.remove_association_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_remove_association_unary_rest_required_fields( + request_type=compute.RemoveAssociationRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).remove_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "name", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.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.remove_association_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_association_unary_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "name", + "requestId", + ) + ) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_remove_association_unary_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.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.remove_association_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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/removeAssociation" + % client.transport._host, + args[1], + ) + + +def test_remove_association_unary_rest_flattened_error(transport: str = "rest"): + client = RegionNetworkPoliciesClient( + 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.remove_association_unary( + compute.RemoveAssociationRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + ) + + +def test_remove_traffic_classification_rule_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 = RegionNetworkPoliciesClient( + 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.remove_traffic_classification_rule + 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.remove_traffic_classification_rule + ] = mock_rpc + + request = {} + client.remove_traffic_classification_rule(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.remove_traffic_classification_rule(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_remove_traffic_classification_rule_rest_required_fields( + request_type=compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).remove_traffic_classification_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_traffic_classification_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "priority", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.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.remove_traffic_classification_rule(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_traffic_classification_rule_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.remove_traffic_classification_rule._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "priority", + "requestId", + ) + ) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_remove_traffic_classification_rule_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.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.remove_traffic_classification_rule(**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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/removeTrafficClassificationRule" + % client.transport._host, + args[1], + ) + + +def test_remove_traffic_classification_rule_rest_flattened_error( + transport: str = "rest", +): + client = RegionNetworkPoliciesClient( + 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.remove_traffic_classification_rule( + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + ) + + +def test_remove_traffic_classification_rule_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 = RegionNetworkPoliciesClient( + 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.remove_traffic_classification_rule + 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.remove_traffic_classification_rule + ] = mock_rpc + + request = {} + client.remove_traffic_classification_rule_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.remove_traffic_classification_rule_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_remove_traffic_classification_rule_unary_rest_required_fields( + request_type=compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, +): + transport_class = transports.RegionNetworkPoliciesRestTransport + + request_init = {} + request_init["network_policy"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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() + ).remove_traffic_classification_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["networkPolicy"] = "network_policy_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_traffic_classification_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "priority", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "networkPolicy" in jsonified_request + assert jsonified_request["networkPolicy"] == "network_policy_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionNetworkPoliciesClient( + 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.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.remove_traffic_classification_rule_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_traffic_classification_rule_unary_rest_unset_required_fields(): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.remove_traffic_classification_rule._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "priority", + "requestId", + ) + ) + & set( + ( + "networkPolicy", + "project", + "region", + ) + ) + ) + + +def test_remove_traffic_classification_rule_unary_rest_flattened(): + client = RegionNetworkPoliciesClient( + 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", + "region": "sample2", + "network_policy": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + network_policy="network_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.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.remove_traffic_classification_rule_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/beta/projects/{project}/regions/{region}/networkPolicies/{network_policy}/removeTrafficClassificationRule" + % client.transport._host, + args[1], + ) + + +def test_remove_traffic_classification_rule_unary_rest_flattened_error( + transport: str = "rest", +): + client = RegionNetworkPoliciesClient( + 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.remove_traffic_classification_rule_unary( + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest(), + project="project_value", + region="region_value", + network_policy="network_policy_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionNetworkPoliciesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionNetworkPoliciesClient( + 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 = RegionNetworkPoliciesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionNetworkPoliciesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionNetworkPoliciesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionNetworkPoliciesRestTransport, + ], +) +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 = RegionNetworkPoliciesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_add_association_rest_bad_request( + request_type=compute.AddAssociationRegionNetworkPolicyRequest, +): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.add_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AddAssociationRegionNetworkPolicyRequest, + dict, + ], +) +def test_add_association_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + request_init["network_policy_association_resource"] = { + "attachment_target": "attachment_target_value", + "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.AddAssociationRegionNetworkPolicyRequest.meta.fields[ + "network_policy_association_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[ + "network_policy_association_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["network_policy_association_resource"][field]) + ): + del request_init["network_policy_association_resource"][field][i][ + subfield + ] + else: + del request_init["network_policy_association_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.add_association(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_add_association_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_add_association" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "post_add_association_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_add_association" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AddAssociationRegionNetworkPolicyRequest.pb( + compute.AddAssociationRegionNetworkPolicyRequest() + ) + 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.AddAssociationRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.add_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_add_traffic_classification_rule_rest_bad_request( + request_type=compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest, +): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.add_traffic_classification_rule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest, + dict, + ], +) +def test_add_traffic_classification_rule_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + request_init["network_policy_traffic_classification_rule_resource"] = { + "action": { + "dscp_mode": "dscp_mode_value", + "dscp_value": 1062, + "traffic_class": "traffic_class_value", + "type_": "type__value", + }, + "description": "description_value", + "disabled": True, + "kind": "kind_value", + "match": { + "dest_ip_ranges": ["dest_ip_ranges_value1", "dest_ip_ranges_value2"], + "layer4_configs": [ + { + "ip_protocol": "ip_protocol_value", + "ports": ["ports_value1", "ports_value2"], + } + ], + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"], + }, + "priority": 898, + "rule_name": "rule_name_value", + "rule_tuple_count": 1737, + "target_secure_tags": [{"name": "name_value", "state": "state_value"}], + "target_service_accounts": [ + "target_service_accounts_value1", + "target_service_accounts_value2", + ], + } + # 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.AddTrafficClassificationRuleRegionNetworkPolicyRequest.meta.fields[ + "network_policy_traffic_classification_rule_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[ + "network_policy_traffic_classification_rule_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[ + "network_policy_traffic_classification_rule_resource" + ][field] + ), + ): + del request_init[ + "network_policy_traffic_classification_rule_resource" + ][field][i][subfield] + else: + del request_init["network_policy_traffic_classification_rule_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.add_traffic_classification_rule(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_add_traffic_classification_rule_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, + "post_add_traffic_classification_rule", + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "post_add_traffic_classification_rule_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "pre_add_traffic_classification_rule", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest.pb( + compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest() + ) + 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.AddTrafficClassificationRuleRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.add_traffic_classification_rule( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_aggregated_list_rest_bad_request( + request_type=compute.AggregatedListRegionNetworkPoliciesRequest, +): + client = RegionNetworkPoliciesClient( + 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.AggregatedListRegionNetworkPoliciesRequest, + dict, + ], +) +def test_aggregated_list_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + 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.NetworkPolicyAggregatedList( + 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.NetworkPolicyAggregatedList.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.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.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_aggregated_list" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "post_aggregated_list_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_aggregated_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AggregatedListRegionNetworkPoliciesRequest.pb( + compute.AggregatedListRegionNetworkPoliciesRequest() + ) + 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.NetworkPolicyAggregatedList.to_json( + compute.NetworkPolicyAggregatedList() + ) + req.return_value.content = return_value + + request = compute.AggregatedListRegionNetworkPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.NetworkPolicyAggregatedList() + post_with_metadata.return_value = ( + compute.NetworkPolicyAggregatedList(), + 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.DeleteRegionNetworkPolicyRequest): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.DeleteRegionNetworkPolicyRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "post_delete_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteRegionNetworkPolicyRequest.pb( + compute.DeleteRegionNetworkPolicyRequest() + ) + 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.DeleteRegionNetworkPolicyRequest() + 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.GetRegionNetworkPolicyRequest): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.GetRegionNetworkPolicyRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.NetworkPolicy( + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + kind="kind_value", + name="name_value", + region="region_value", + rule_tuple_count=1737, + 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.NetworkPolicy.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.NetworkPolicy) + 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.region == "region_value" + assert response.rule_tuple_count == 1737 + 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.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRegionNetworkPolicyRequest.pb( + compute.GetRegionNetworkPolicyRequest() + ) + 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.NetworkPolicy.to_json(compute.NetworkPolicy()) + req.return_value.content = return_value + + request = compute.GetRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.NetworkPolicy() + post_with_metadata.return_value = compute.NetworkPolicy(), 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_association_rest_bad_request( + request_type=compute.GetAssociationRegionNetworkPolicyRequest, +): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetAssociationRegionNetworkPolicyRequest, + dict, + ], +) +def test_get_association_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.NetworkPolicyAssociation( + attachment_target="attachment_target_value", + name="name_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.NetworkPolicyAssociation.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_association(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.NetworkPolicyAssociation) + assert response.attachment_target == "attachment_target_value" + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_association_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_get_association" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "post_get_association_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_get_association" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetAssociationRegionNetworkPolicyRequest.pb( + compute.GetAssociationRegionNetworkPolicyRequest() + ) + 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.NetworkPolicyAssociation.to_json( + compute.NetworkPolicyAssociation() + ) + req.return_value.content = return_value + + request = compute.GetAssociationRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.NetworkPolicyAssociation() + post_with_metadata.return_value = compute.NetworkPolicyAssociation(), metadata + + client.get_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_traffic_classification_rule_rest_bad_request( + request_type=compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest, +): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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_traffic_classification_rule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest, + dict, + ], +) +def test_get_traffic_classification_rule_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.NetworkPolicyTrafficClassificationRule( + description="description_value", + disabled=True, + kind="kind_value", + priority=898, + rule_name="rule_name_value", + rule_tuple_count=1737, + target_service_accounts=["target_service_accounts_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.NetworkPolicyTrafficClassificationRule.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_traffic_classification_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.NetworkPolicyTrafficClassificationRule) + assert response.description == "description_value" + assert response.disabled is True + assert response.kind == "kind_value" + assert response.priority == 898 + assert response.rule_name == "rule_name_value" + assert response.rule_tuple_count == 1737 + assert response.target_service_accounts == ["target_service_accounts_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_traffic_classification_rule_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, + "post_get_traffic_classification_rule", + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "post_get_traffic_classification_rule_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "pre_get_traffic_classification_rule", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest.pb( + compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest() + ) + 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.NetworkPolicyTrafficClassificationRule.to_json( + compute.NetworkPolicyTrafficClassificationRule() + ) + req.return_value.content = return_value + + request = compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.NetworkPolicyTrafficClassificationRule() + post_with_metadata.return_value = ( + compute.NetworkPolicyTrafficClassificationRule(), + metadata, + ) + + client.get_traffic_classification_rule( + 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.InsertRegionNetworkPolicyRequest): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "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.insert(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertRegionNetworkPolicyRequest, + dict, + ], +) +def test_insert_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["network_policy_resource"] = { + "associations": [ + {"attachment_target": "attachment_target_value", "name": "name_value"} + ], + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "region": "region_value", + "rule_tuple_count": 1737, + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "traffic_classification_rules": [ + { + "action": { + "dscp_mode": "dscp_mode_value", + "dscp_value": 1062, + "traffic_class": "traffic_class_value", + "type_": "type__value", + }, + "description": "description_value", + "disabled": True, + "kind": "kind_value", + "match": { + "dest_ip_ranges": [ + "dest_ip_ranges_value1", + "dest_ip_ranges_value2", + ], + "layer4_configs": [ + { + "ip_protocol": "ip_protocol_value", + "ports": ["ports_value1", "ports_value2"], + } + ], + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"], + }, + "priority": 898, + "rule_name": "rule_name_value", + "rule_tuple_count": 1737, + "target_secure_tags": [{"name": "name_value", "state": "state_value"}], + "target_service_accounts": [ + "target_service_accounts_value1", + "target_service_accounts_value2", + ], + } + ], + } + # 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.InsertRegionNetworkPolicyRequest.meta.fields[ + "network_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[ + "network_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["network_policy_resource"][field])): + del request_init["network_policy_resource"][field][i][subfield] + else: + del request_init["network_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.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "post_insert_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.InsertRegionNetworkPolicyRequest.pb( + compute.InsertRegionNetworkPolicyRequest() + ) + 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.InsertRegionNetworkPolicyRequest() + 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.ListRegionNetworkPoliciesRequest): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "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.list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListRegionNetworkPoliciesRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "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.NetworkPolicyList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_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.NetworkPolicyList.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.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListRegionNetworkPoliciesRequest.pb( + compute.ListRegionNetworkPoliciesRequest() + ) + 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.NetworkPolicyList.to_json(compute.NetworkPolicyList()) + req.return_value.content = return_value + + request = compute.ListRegionNetworkPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.NetworkPolicyList() + post_with_metadata.return_value = compute.NetworkPolicyList(), 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_patch_rest_bad_request(request_type=compute.PatchRegionNetworkPolicyRequest): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.patch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.PatchRegionNetworkPolicyRequest, + dict, + ], +) +def test_patch_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + request_init["network_policy_resource"] = { + "associations": [ + {"attachment_target": "attachment_target_value", "name": "name_value"} + ], + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "region": "region_value", + "rule_tuple_count": 1737, + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "traffic_classification_rules": [ + { + "action": { + "dscp_mode": "dscp_mode_value", + "dscp_value": 1062, + "traffic_class": "traffic_class_value", + "type_": "type__value", + }, + "description": "description_value", + "disabled": True, + "kind": "kind_value", + "match": { + "dest_ip_ranges": [ + "dest_ip_ranges_value1", + "dest_ip_ranges_value2", + ], + "layer4_configs": [ + { + "ip_protocol": "ip_protocol_value", + "ports": ["ports_value1", "ports_value2"], + } + ], + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"], + }, + "priority": 898, + "rule_name": "rule_name_value", + "rule_tuple_count": 1737, + "target_secure_tags": [{"name": "name_value", "state": "state_value"}], + "target_service_accounts": [ + "target_service_accounts_value1", + "target_service_accounts_value2", + ], + } + ], + } + # 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.PatchRegionNetworkPolicyRequest.meta.fields[ + "network_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[ + "network_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["network_policy_resource"][field])): + del request_init["network_policy_resource"][field][i][subfield] + else: + del request_init["network_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.patch(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_patch_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_patch" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "post_patch_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_patch" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.PatchRegionNetworkPolicyRequest.pb( + compute.PatchRegionNetworkPolicyRequest() + ) + 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.PatchRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.patch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_patch_traffic_classification_rule_rest_bad_request( + request_type=compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, +): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.patch_traffic_classification_rule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest, + dict, + ], +) +def test_patch_traffic_classification_rule_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + request_init["network_policy_traffic_classification_rule_resource"] = { + "action": { + "dscp_mode": "dscp_mode_value", + "dscp_value": 1062, + "traffic_class": "traffic_class_value", + "type_": "type__value", + }, + "description": "description_value", + "disabled": True, + "kind": "kind_value", + "match": { + "dest_ip_ranges": ["dest_ip_ranges_value1", "dest_ip_ranges_value2"], + "layer4_configs": [ + { + "ip_protocol": "ip_protocol_value", + "ports": ["ports_value1", "ports_value2"], + } + ], + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"], + }, + "priority": 898, + "rule_name": "rule_name_value", + "rule_tuple_count": 1737, + "target_secure_tags": [{"name": "name_value", "state": "state_value"}], + "target_service_accounts": [ + "target_service_accounts_value1", + "target_service_accounts_value2", + ], + } + # 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.PatchTrafficClassificationRuleRegionNetworkPolicyRequest.meta.fields[ + "network_policy_traffic_classification_rule_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[ + "network_policy_traffic_classification_rule_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[ + "network_policy_traffic_classification_rule_resource" + ][field] + ), + ): + del request_init[ + "network_policy_traffic_classification_rule_resource" + ][field][i][subfield] + else: + del request_init["network_policy_traffic_classification_rule_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.patch_traffic_classification_rule(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_patch_traffic_classification_rule_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, + "post_patch_traffic_classification_rule", + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "post_patch_traffic_classification_rule_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "pre_patch_traffic_classification_rule", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest.pb( + compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest() + ) + ) + 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.PatchTrafficClassificationRuleRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.patch_traffic_classification_rule( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_remove_association_rest_bad_request( + request_type=compute.RemoveAssociationRegionNetworkPolicyRequest, +): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.remove_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.RemoveAssociationRegionNetworkPolicyRequest, + dict, + ], +) +def test_remove_association_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.remove_association(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_remove_association_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, "post_remove_association" + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "post_remove_association_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, "pre_remove_association" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.RemoveAssociationRegionNetworkPolicyRequest.pb( + compute.RemoveAssociationRegionNetworkPolicyRequest() + ) + 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.RemoveAssociationRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.remove_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_remove_traffic_classification_rule_rest_bad_request( + request_type=compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, +): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.remove_traffic_classification_rule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest, + dict, + ], +) +def test_remove_traffic_classification_rule_rest_call_success(request_type): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "network_policy": "sample3", + } + 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.remove_traffic_classification_rule(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_remove_traffic_classification_rule_rest_interceptors(null_interceptor): + transport = transports.RegionNetworkPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionNetworkPoliciesRestInterceptor(), + ) + client = RegionNetworkPoliciesClient(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.RegionNetworkPoliciesRestInterceptor, + "post_remove_traffic_classification_rule", + ) as post, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "post_remove_traffic_classification_rule_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.RegionNetworkPoliciesRestInterceptor, + "pre_remove_traffic_classification_rule", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest.pb( + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest() + ) + ) + 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.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.remove_traffic_classification_rule( + 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 = RegionNetworkPoliciesClient( + 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_add_association_unary_empty_call_rest(): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_association), "__call__") as call: + client.add_association_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.AddAssociationRegionNetworkPolicyRequest() + + 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_add_traffic_classification_rule_unary_empty_call_rest(): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_traffic_classification_rule), "__call__" + ) as call: + client.add_traffic_classification_rule_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.AddTrafficClassificationRuleRegionNetworkPolicyRequest() + + 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_aggregated_list_empty_call_rest(): + client = RegionNetworkPoliciesClient( + 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.AggregatedListRegionNetworkPoliciesRequest() + + 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 = RegionNetworkPoliciesClient( + 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.DeleteRegionNetworkPolicyRequest() + + 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 = RegionNetworkPoliciesClient( + 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.GetRegionNetworkPolicyRequest() + + 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_association_empty_call_rest(): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_association), "__call__") as call: + client.get_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetAssociationRegionNetworkPolicyRequest() + + 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_traffic_classification_rule_empty_call_rest(): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_traffic_classification_rule), "__call__" + ) as call: + client.get_traffic_classification_rule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetTrafficClassificationRuleRegionNetworkPolicyRequest() + + 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 = RegionNetworkPoliciesClient( + 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.InsertRegionNetworkPolicyRequest() + + 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 = RegionNetworkPoliciesClient( + 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.ListRegionNetworkPoliciesRequest() + + 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_patch_unary_empty_call_rest(): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.patch), "__call__") as call: + client.patch_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PatchRegionNetworkPolicyRequest() + + 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_patch_traffic_classification_rule_unary_empty_call_rest(): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.patch_traffic_classification_rule), "__call__" + ) as call: + client.patch_traffic_classification_rule_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PatchTrafficClassificationRuleRegionNetworkPolicyRequest() + + 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_remove_association_unary_empty_call_rest(): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_association), "__call__" + ) as call: + client.remove_association_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.RemoveAssociationRegionNetworkPolicyRequest() + + 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_remove_traffic_classification_rule_unary_empty_call_rest(): + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_traffic_classification_rule), "__call__" + ) as call: + client.remove_traffic_classification_rule_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + compute.RemoveTrafficClassificationRuleRegionNetworkPolicyRequest() + ) + + assert args[0] == request_msg + + +def test_region_network_policies_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionNetworkPoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_region_network_policies_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.region_network_policies.transports.RegionNetworkPoliciesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RegionNetworkPoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "add_association", + "add_traffic_classification_rule", + "aggregated_list", + "delete", + "get", + "get_association", + "get_traffic_classification_rule", + "insert", + "list", + "patch", + "patch_traffic_classification_rule", + "remove_association", + "remove_traffic_classification_rule", + ) + 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_region_network_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_v1beta.services.region_network_policies.transports.RegionNetworkPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionNetworkPoliciesTransport( + 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_region_network_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_v1beta.services.region_network_policies.transports.RegionNetworkPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionNetworkPoliciesTransport() + adc.assert_called_once() + + +def test_region_network_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) + RegionNetworkPoliciesClient() + 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_region_network_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.RegionNetworkPoliciesRestTransport( + 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_region_network_policies_host_no_port(transport_name): + client = RegionNetworkPoliciesClient( + 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_region_network_policies_host_with_port(transport_name): + client = RegionNetworkPoliciesClient( + 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_region_network_policies_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionNetworkPoliciesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionNetworkPoliciesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.add_association._session + session2 = client2.transport.add_association._session + assert session1 != session2 + session1 = client1.transport.add_traffic_classification_rule._session + session2 = client2.transport.add_traffic_classification_rule._session + assert session1 != session2 + 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.get_association._session + session2 = client2.transport.get_association._session + assert session1 != session2 + session1 = client1.transport.get_traffic_classification_rule._session + session2 = client2.transport.get_traffic_classification_rule._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.patch._session + session2 = client2.transport.patch._session + assert session1 != session2 + session1 = client1.transport.patch_traffic_classification_rule._session + session2 = client2.transport.patch_traffic_classification_rule._session + assert session1 != session2 + session1 = client1.transport.remove_association._session + session2 = client2.transport.remove_association._session + assert session1 != session2 + session1 = client1.transport.remove_traffic_classification_rule._session + session2 = client2.transport.remove_traffic_classification_rule._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RegionNetworkPoliciesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegionNetworkPoliciesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionNetworkPoliciesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RegionNetworkPoliciesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegionNetworkPoliciesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionNetworkPoliciesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = RegionNetworkPoliciesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegionNetworkPoliciesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionNetworkPoliciesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RegionNetworkPoliciesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegionNetworkPoliciesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionNetworkPoliciesClient.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 = RegionNetworkPoliciesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegionNetworkPoliciesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionNetworkPoliciesClient.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.RegionNetworkPoliciesTransport, "_prep_wrapped_messages" + ) as prep: + client = RegionNetworkPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RegionNetworkPoliciesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RegionNetworkPoliciesClient.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 = RegionNetworkPoliciesClient( + 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 = RegionNetworkPoliciesClient( + 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", + [ + (RegionNetworkPoliciesClient, transports.RegionNetworkPoliciesRestTransport), + ], +) +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-v1beta/tests/unit/gapic/compute_v1beta/test_region_snapshots.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_snapshots.py index a39ebce73203..4b9c7c115513 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_snapshots.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_snapshots.py @@ -3956,6 +3956,7 @@ def test_insert_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "location_hint": "location_hint_value", "name": "name_value", + "params": {"resource_manager_tags": {}}, "region": "region_value", "satisfies_pzi": True, "satisfies_pzs": True, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_sub_blocks.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_sub_blocks.py index 55bffa40e5e0..b7e890a511f6 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_sub_blocks.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_sub_blocks.py @@ -1933,6 +1933,456 @@ def test_perform_maintenance_unary_rest_flattened_error(transport: str = "rest") ) +def test_report_faulty_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 = ReservationSubBlocksClient( + 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.report_faulty 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.report_faulty] = mock_rpc + + request = {} + client.report_faulty(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.report_faulty(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_report_faulty_rest_required_fields( + request_type=compute.ReportFaultyReservationSubBlockRequest, +): + transport_class = transports.ReservationSubBlocksRestTransport + + request_init = {} + request_init["parent_name"] = "" + request_init["project"] = "" + request_init["reservation_sub_block"] = "" + request_init["zone"] = "" + 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() + ).report_faulty._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parentName"] = "parent_name_value" + jsonified_request["project"] = "project_value" + jsonified_request["reservationSubBlock"] = "reservation_sub_block_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_faulty._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 "parentName" in jsonified_request + assert jsonified_request["parentName"] == "parent_name_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "reservationSubBlock" in jsonified_request + assert jsonified_request["reservationSubBlock"] == "reservation_sub_block_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = ReservationSubBlocksClient( + 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.report_faulty(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_report_faulty_rest_unset_required_fields(): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.report_faulty._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "parentName", + "project", + "reservationSubBlock", + "reservationSubBlocksReportFaultyRequestResource", + "zone", + ) + ) + ) + + +def test_report_faulty_rest_flattened(): + client = ReservationSubBlocksClient( + 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", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + reservation_sub_blocks_report_faulty_request_resource=compute.ReservationSubBlocksReportFaultyRequest( + disruption_schedule="disruption_schedule_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.report_faulty(**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/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty" + % client.transport._host, + args[1], + ) + + +def test_report_faulty_rest_flattened_error(transport: str = "rest"): + client = ReservationSubBlocksClient( + 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.report_faulty( + compute.ReportFaultyReservationSubBlockRequest(), + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + reservation_sub_blocks_report_faulty_request_resource=compute.ReservationSubBlocksReportFaultyRequest( + disruption_schedule="disruption_schedule_value" + ), + ) + + +def test_report_faulty_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 = ReservationSubBlocksClient( + 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.report_faulty 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.report_faulty] = mock_rpc + + request = {} + client.report_faulty_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.report_faulty_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_report_faulty_unary_rest_required_fields( + request_type=compute.ReportFaultyReservationSubBlockRequest, +): + transport_class = transports.ReservationSubBlocksRestTransport + + request_init = {} + request_init["parent_name"] = "" + request_init["project"] = "" + request_init["reservation_sub_block"] = "" + request_init["zone"] = "" + 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() + ).report_faulty._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parentName"] = "parent_name_value" + jsonified_request["project"] = "project_value" + jsonified_request["reservationSubBlock"] = "reservation_sub_block_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_faulty._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 "parentName" in jsonified_request + assert jsonified_request["parentName"] == "parent_name_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "reservationSubBlock" in jsonified_request + assert jsonified_request["reservationSubBlock"] == "reservation_sub_block_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = ReservationSubBlocksClient( + 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.report_faulty_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_report_faulty_unary_rest_unset_required_fields(): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.report_faulty._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "parentName", + "project", + "reservationSubBlock", + "reservationSubBlocksReportFaultyRequestResource", + "zone", + ) + ) + ) + + +def test_report_faulty_unary_rest_flattened(): + client = ReservationSubBlocksClient( + 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", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + reservation_sub_blocks_report_faulty_request_resource=compute.ReservationSubBlocksReportFaultyRequest( + disruption_schedule="disruption_schedule_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.report_faulty_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/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty" + % client.transport._host, + args[1], + ) + + +def test_report_faulty_unary_rest_flattened_error(transport: str = "rest"): + client = ReservationSubBlocksClient( + 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.report_faulty_unary( + compute.ReportFaultyReservationSubBlockRequest(), + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + reservation_sub_blocks_report_faulty_request_resource=compute.ReservationSubBlocksReportFaultyRequest( + disruption_schedule="disruption_schedule_value" + ), + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ReservationSubBlocksRestTransport( @@ -2468,6 +2918,275 @@ def test_perform_maintenance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_report_faulty_rest_bad_request( + request_type=compute.ReportFaultyReservationSubBlockRequest, +): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + 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.report_faulty(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ReportFaultyReservationSubBlockRequest, + dict, + ], +) +def test_report_faulty_rest_call_success(request_type): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + request_init["reservation_sub_blocks_report_faulty_request_resource"] = { + "disruption_schedule": "disruption_schedule_value", + "failure_component": "failure_component_value", + "fault_reasons": [ + {"behavior": "behavior_value", "description": "description_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.ReportFaultyReservationSubBlockRequest.meta.fields[ + "reservation_sub_blocks_report_faulty_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[ + "reservation_sub_blocks_report_faulty_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[ + "reservation_sub_blocks_report_faulty_request_resource" + ][field] + ), + ): + del request_init[ + "reservation_sub_blocks_report_faulty_request_resource" + ][field][i][subfield] + else: + del request_init[ + "reservation_sub_blocks_report_faulty_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.report_faulty(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_report_faulty_rest_interceptors(null_interceptor): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationSubBlocksRestInterceptor(), + ) + client = ReservationSubBlocksClient(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.ReservationSubBlocksRestInterceptor, "post_report_faulty" + ) as post, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, + "post_report_faulty_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, "pre_report_faulty" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ReportFaultyReservationSubBlockRequest.pb( + compute.ReportFaultyReservationSubBlockRequest() + ) + 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.ReportFaultyReservationSubBlockRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.report_faulty( + 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 = ReservationSubBlocksClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2537,6 +3256,26 @@ def test_perform_maintenance_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_report_faulty_unary_empty_call_rest(): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.report_faulty), "__call__") as call: + client.report_faulty_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ReportFaultyReservationSubBlockRequest() + + assert args[0] == request_msg + + def test_reservation_sub_blocks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -2562,6 +3301,7 @@ def test_reservation_sub_blocks_base_transport(): "get", "list", "perform_maintenance", + "report_faulty", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2708,6 +3448,9 @@ def test_reservation_sub_blocks_client_transport_session_collision(transport_nam session1 = client1.transport.perform_maintenance._session session2 = client2.transport.perform_maintenance._session assert session1 != session2 + session1 = client1.transport.report_faulty._session + session2 = client2.transport.report_faulty._session + assert session1 != session2 def test_common_billing_account_path(): diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_snapshots.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_snapshots.py index 17f204f9d325..83268cde2704 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_snapshots.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_snapshots.py @@ -4190,6 +4190,7 @@ def test_insert_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "location_hint": "location_hint_value", "name": "name_value", + "params": {"resource_manager_tags": {}}, "region": "region_value", "satisfies_pzi": True, "satisfies_pzs": True, diff --git a/packages/google-cloud-compute/docs/compute_v1/organization_security_policies.rst b/packages/google-cloud-compute/docs/compute_v1/organization_security_policies.rst new file mode 100644 index 000000000000..04652e90fe8c --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/organization_security_policies.rst @@ -0,0 +1,10 @@ +OrganizationSecurityPolicies +---------------------------------------------- + +.. automodule:: google.cloud.compute_v1.services.organization_security_policies + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.organization_security_policies.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/preview_features.rst b/packages/google-cloud-compute/docs/compute_v1/preview_features.rst new file mode 100644 index 000000000000..49ab4acc2cb9 --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/preview_features.rst @@ -0,0 +1,10 @@ +PreviewFeatures +--------------------------------- + +.. automodule:: google.cloud.compute_v1.services.preview_features + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.preview_features.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 b84aa67a8fe8..ea980a658598 100644 --- a/packages/google-cloud-compute/docs/compute_v1/services_.rst +++ b/packages/google-cloud-compute/docs/compute_v1/services_.rst @@ -49,7 +49,9 @@ Services for Google Cloud Compute v1 API node_groups node_templates node_types + organization_security_policies packet_mirrorings + preview_features projects public_advertised_prefixes public_delegated_prefixes diff --git a/packages/google-cloud-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index aef642c6c51c..1c0e2ce8c375 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -118,9 +118,15 @@ from google.cloud.compute_v1.services.node_groups.client import NodeGroupsClient from google.cloud.compute_v1.services.node_templates.client import NodeTemplatesClient from google.cloud.compute_v1.services.node_types.client import NodeTypesClient +from google.cloud.compute_v1.services.organization_security_policies.client import ( + OrganizationSecurityPoliciesClient, +) from google.cloud.compute_v1.services.packet_mirrorings.client import ( PacketMirroringsClient, ) +from google.cloud.compute_v1.services.preview_features.client import ( + PreviewFeaturesClient, +) from google.cloud.compute_v1.services.projects.client import ProjectsClient from google.cloud.compute_v1.services.public_advertised_prefixes.client import ( PublicAdvertisedPrefixesClient, @@ -266,6 +272,7 @@ AddAccessConfigInstanceRequest, AddAssociationFirewallPolicyRequest, AddAssociationNetworkFirewallPolicyRequest, + AddAssociationOrganizationSecurityPolicyRequest, AddAssociationRegionNetworkFirewallPolicyRequest, AddHealthCheckTargetPoolRequest, AddInstancesInstanceGroupRequest, @@ -283,6 +290,7 @@ AddressList, AddRuleFirewallPolicyRequest, AddRuleNetworkFirewallPolicyRequest, + AddRuleOrganizationSecurityPolicyRequest, AddRuleRegionNetworkFirewallPolicyRequest, AddRuleRegionSecurityPolicyRequest, AddRuleSecurityPolicyRequest, @@ -440,6 +448,7 @@ ConnectionDraining, ConsistentHashLoadBalancerSettings, ConsistentHashLoadBalancerSettingsHttpCookie, + CopyRulesOrganizationSecurityPolicyRequest, CorsPolicy, CreateInstancesInstanceGroupManagerRequest, CreateInstancesRegionInstanceGroupManagerRequest, @@ -451,6 +460,7 @@ CustomErrorResponsePolicy, CustomErrorResponsePolicyCustomErrorResponseRule, Data, + Date, DeleteAccessConfigInstanceRequest, DeleteAddressRequest, DeleteAutoscalerRequest, @@ -494,6 +504,7 @@ DeleteNodeGroupRequest, DeleteNodesNodeGroupRequest, DeleteNodeTemplateRequest, + DeleteOrganizationSecurityPolicyRequest, DeletePacketMirroringRequest, DeletePerInstanceConfigsInstanceGroupManagerRequest, DeletePerInstanceConfigsRegionInstanceGroupManagerRequest, @@ -617,6 +628,7 @@ GetAddressRequest, GetAssociationFirewallPolicyRequest, GetAssociationNetworkFirewallPolicyRequest, + GetAssociationOrganizationSecurityPolicyRequest, GetAssociationRegionNetworkFirewallPolicyRequest, GetAutoscalerRequest, GetBackendBucketRequest, @@ -627,6 +639,8 @@ GetEffectiveFirewallsInstanceRequest, GetEffectiveFirewallsNetworkRequest, GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest, + GetEffectiveSecurityPoliciesBackendServiceRequest, + GetEffectiveSecurityPoliciesBackendServiceResponse, GetExternalVpnGatewayRequest, GetFirewallPolicyRequest, GetFirewallRequest, @@ -702,8 +716,10 @@ GetNodeTypeRequest, GetOperationalStatusInterconnectAttachmentGroupRequest, GetOperationalStatusInterconnectGroupRequest, + GetOrganizationSecurityPolicyRequest, GetPacketMirroringRequest, GetPacketMirroringRuleNetworkFirewallPolicyRequest, + GetPreviewFeatureRequest, GetProjectRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, @@ -740,6 +756,7 @@ GetRouterStatusRouterRequest, GetRuleFirewallPolicyRequest, GetRuleNetworkFirewallPolicyRequest, + GetRuleOrganizationSecurityPolicyRequest, GetRuleRegionNetworkFirewallPolicyRequest, GetRuleRegionSecurityPolicyRequest, GetRuleSecurityPolicyRequest, @@ -815,6 +832,7 @@ Image, ImageFamilyView, ImageList, + ImageParams, InitialStateConfig, InsertAddressRequest, InsertAutoscalerRequest, @@ -850,6 +868,7 @@ InsertNetworkRequest, InsertNodeGroupRequest, InsertNodeTemplateRequest, + InsertOrganizationSecurityPolicyRequest, InsertPacketMirroringRequest, InsertPublicAdvertisedPrefixeRequest, InsertPublicDelegatedPrefixeRequest, @@ -1065,6 +1084,7 @@ ListAcceleratorTypesRequest, ListAddressesRequest, ListAssociationsFirewallPolicyRequest, + ListAssociationsOrganizationSecurityPolicyRequest, ListAutoscalersRequest, ListAvailableFeaturesRegionSslPoliciesRequest, ListAvailableFeaturesSslPoliciesRequest, @@ -1119,11 +1139,14 @@ ListNodesNodeGroupsRequest, ListNodeTemplatesRequest, ListNodeTypesRequest, + ListOrganizationSecurityPoliciesRequest, ListPacketMirroringsRequest, ListPeeringRoutesNetworksRequest, ListPerInstanceConfigsInstanceGroupManagersRequest, ListPerInstanceConfigsRegionInstanceGroupManagersRequest, + ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, ListPreconfiguredExpressionSetsSecurityPoliciesRequest, + ListPreviewFeaturesRequest, ListPublicAdvertisedPrefixesRequest, ListPublicDelegatedPrefixesRequest, ListReferrersInstancesRequest, @@ -1208,6 +1231,7 @@ MoveFirewallPolicyRequest, MoveGlobalAddressRequest, MoveInstanceProjectRequest, + MoveOrganizationSecurityPolicyRequest, NamedPort, NatIpInfo, NatIpInfoNatIpInfoMapping, @@ -1285,6 +1309,7 @@ OperationAggregatedList, OperationList, OperationsScopedList, + OrganizationSecurityPoliciesListAssociationsResponse, OutlierDetection, PacketIntervals, PacketMirroring, @@ -1318,6 +1343,7 @@ PatchNetworkFirewallPolicyRequest, PatchNetworkRequest, PatchNodeGroupRequest, + PatchOrganizationSecurityPolicyRequest, PatchPacketMirroringRequest, PatchPacketMirroringRuleNetworkFirewallPolicyRequest, PatchPerInstanceConfigsInstanceGroupManagerRequest, @@ -1339,6 +1365,7 @@ PatchRouterRequest, PatchRuleFirewallPolicyRequest, PatchRuleNetworkFirewallPolicyRequest, + PatchRuleOrganizationSecurityPolicyRequest, PatchRuleRegionNetworkFirewallPolicyRequest, PatchRuleRegionSecurityPolicyRequest, PatchRuleSecurityPolicyRequest, @@ -1365,6 +1392,12 @@ PreservedStatePreservedDisk, PreservedStatePreservedNetworkIp, PreservedStatePreservedNetworkIpIpAddress, + PreviewFeature, + PreviewFeatureList, + PreviewFeatureRolloutOperation, + PreviewFeatureRolloutOperationRolloutInput, + PreviewFeatureStatus, + PreviewFeatureStatusReleaseStatus, PreviewRouterRequest, Project, ProjectsDisableXpnResourceRequest, @@ -1429,6 +1462,7 @@ RegionUrlMapsValidateRequest, RemoveAssociationFirewallPolicyRequest, RemoveAssociationNetworkFirewallPolicyRequest, + RemoveAssociationOrganizationSecurityPolicyRequest, RemoveAssociationRegionNetworkFirewallPolicyRequest, RemoveHealthCheckTargetPoolRequest, RemoveInstancesInstanceGroupRequest, @@ -1440,9 +1474,11 @@ RemoveResourcePoliciesRegionDiskRequest, RemoveRuleFirewallPolicyRequest, RemoveRuleNetworkFirewallPolicyRequest, + RemoveRuleOrganizationSecurityPolicyRequest, RemoveRuleRegionNetworkFirewallPolicyRequest, RemoveRuleRegionSecurityPolicyRequest, RemoveRuleSecurityPolicyRequest, + ReportFaultyReservationSubBlockRequest, ReportHostAsFaultyInstanceRequest, RequestMirrorPolicy, RequestRemovePeeringNetworkRequest, @@ -1467,6 +1503,8 @@ ReservationSubBlockPhysicalTopology, ReservationSubBlocksGetResponse, ReservationSubBlocksListResponse, + ReservationSubBlocksReportFaultyRequest, + ReservationSubBlocksReportFaultyRequestFaultReason, ResetInstanceRequest, ResizeDiskRequest, ResizeInstanceGroupManagerRequest, @@ -1552,6 +1590,7 @@ SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfigThresholdConfigTrafficGranularityConfig, SecurityPolicyAdvancedOptionsConfig, SecurityPolicyAdvancedOptionsConfigJsonCustomConfig, + SecurityPolicyAssociation, SecurityPolicyDdosProtectionConfig, SecurityPolicyList, SecurityPolicyRecaptchaOptionsConfig, @@ -1693,6 +1732,7 @@ SimulateMaintenanceEventNodeGroupRequest, Snapshot, SnapshotList, + SnapshotParams, SnapshotSettings, SnapshotSettingsStorageLocationSettings, SnapshotSettingsStorageLocationSettingsStorageLocationPreference, @@ -1860,6 +1900,7 @@ UpdatePeeringNetworkRequest, UpdatePerInstanceConfigsInstanceGroupManagerRequest, UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest, + UpdatePreviewFeatureRequest, UpdateRegionAutoscalerRequest, UpdateRegionBackendServiceRequest, UpdateRegionCommitmentRequest, @@ -1975,7 +2016,9 @@ "NodeGroupsClient", "NodeTemplatesClient", "NodeTypesClient", + "OrganizationSecurityPoliciesClient", "PacketMirroringsClient", + "PreviewFeaturesClient", "ProjectsClient", "PublicAdvertisedPrefixesClient", "PublicDelegatedPrefixesClient", @@ -2044,6 +2087,7 @@ "AddAccessConfigInstanceRequest", "AddAssociationFirewallPolicyRequest", "AddAssociationNetworkFirewallPolicyRequest", + "AddAssociationOrganizationSecurityPolicyRequest", "AddAssociationRegionNetworkFirewallPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstancesInstanceGroupRequest", @@ -2061,6 +2105,7 @@ "AddressList", "AddRuleFirewallPolicyRequest", "AddRuleNetworkFirewallPolicyRequest", + "AddRuleOrganizationSecurityPolicyRequest", "AddRuleRegionNetworkFirewallPolicyRequest", "AddRuleRegionSecurityPolicyRequest", "AddRuleSecurityPolicyRequest", @@ -2218,6 +2263,7 @@ "ConnectionDraining", "ConsistentHashLoadBalancerSettings", "ConsistentHashLoadBalancerSettingsHttpCookie", + "CopyRulesOrganizationSecurityPolicyRequest", "CorsPolicy", "CreateInstancesInstanceGroupManagerRequest", "CreateInstancesRegionInstanceGroupManagerRequest", @@ -2229,6 +2275,7 @@ "CustomErrorResponsePolicy", "CustomErrorResponsePolicyCustomErrorResponseRule", "Data", + "Date", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -2272,6 +2319,7 @@ "DeleteNodeGroupRequest", "DeleteNodesNodeGroupRequest", "DeleteNodeTemplateRequest", + "DeleteOrganizationSecurityPolicyRequest", "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", @@ -2395,6 +2443,7 @@ "GetAddressRequest", "GetAssociationFirewallPolicyRequest", "GetAssociationNetworkFirewallPolicyRequest", + "GetAssociationOrganizationSecurityPolicyRequest", "GetAssociationRegionNetworkFirewallPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", @@ -2405,6 +2454,8 @@ "GetEffectiveFirewallsInstanceRequest", "GetEffectiveFirewallsNetworkRequest", "GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest", + "GetEffectiveSecurityPoliciesBackendServiceRequest", + "GetEffectiveSecurityPoliciesBackendServiceResponse", "GetExternalVpnGatewayRequest", "GetFirewallPolicyRequest", "GetFirewallRequest", @@ -2480,8 +2531,10 @@ "GetNodeTypeRequest", "GetOperationalStatusInterconnectAttachmentGroupRequest", "GetOperationalStatusInterconnectGroupRequest", + "GetOrganizationSecurityPolicyRequest", "GetPacketMirroringRequest", "GetPacketMirroringRuleNetworkFirewallPolicyRequest", + "GetPreviewFeatureRequest", "GetProjectRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", @@ -2518,6 +2571,7 @@ "GetRouterStatusRouterRequest", "GetRuleFirewallPolicyRequest", "GetRuleNetworkFirewallPolicyRequest", + "GetRuleOrganizationSecurityPolicyRequest", "GetRuleRegionNetworkFirewallPolicyRequest", "GetRuleRegionSecurityPolicyRequest", "GetRuleSecurityPolicyRequest", @@ -2593,6 +2647,7 @@ "Image", "ImageFamilyView", "ImageList", + "ImageParams", "InitialStateConfig", "InsertAddressRequest", "InsertAutoscalerRequest", @@ -2628,6 +2683,7 @@ "InsertNetworkRequest", "InsertNodeGroupRequest", "InsertNodeTemplateRequest", + "InsertOrganizationSecurityPolicyRequest", "InsertPacketMirroringRequest", "InsertPublicAdvertisedPrefixeRequest", "InsertPublicDelegatedPrefixeRequest", @@ -2843,6 +2899,7 @@ "ListAcceleratorTypesRequest", "ListAddressesRequest", "ListAssociationsFirewallPolicyRequest", + "ListAssociationsOrganizationSecurityPolicyRequest", "ListAutoscalersRequest", "ListAvailableFeaturesRegionSslPoliciesRequest", "ListAvailableFeaturesSslPoliciesRequest", @@ -2897,11 +2954,14 @@ "ListNodesNodeGroupsRequest", "ListNodeTemplatesRequest", "ListNodeTypesRequest", + "ListOrganizationSecurityPoliciesRequest", "ListPacketMirroringsRequest", "ListPeeringRoutesNetworksRequest", "ListPerInstanceConfigsInstanceGroupManagersRequest", "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", + "ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest", "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", + "ListPreviewFeaturesRequest", "ListPublicAdvertisedPrefixesRequest", "ListPublicDelegatedPrefixesRequest", "ListReferrersInstancesRequest", @@ -2986,6 +3046,7 @@ "MoveFirewallPolicyRequest", "MoveGlobalAddressRequest", "MoveInstanceProjectRequest", + "MoveOrganizationSecurityPolicyRequest", "NamedPort", "NatIpInfo", "NatIpInfoNatIpInfoMapping", @@ -3063,6 +3124,7 @@ "OperationAggregatedList", "OperationList", "OperationsScopedList", + "OrganizationSecurityPoliciesListAssociationsResponse", "OutlierDetection", "PacketIntervals", "PacketMirroring", @@ -3096,6 +3158,7 @@ "PatchNetworkFirewallPolicyRequest", "PatchNetworkRequest", "PatchNodeGroupRequest", + "PatchOrganizationSecurityPolicyRequest", "PatchPacketMirroringRequest", "PatchPacketMirroringRuleNetworkFirewallPolicyRequest", "PatchPerInstanceConfigsInstanceGroupManagerRequest", @@ -3117,6 +3180,7 @@ "PatchRouterRequest", "PatchRuleFirewallPolicyRequest", "PatchRuleNetworkFirewallPolicyRequest", + "PatchRuleOrganizationSecurityPolicyRequest", "PatchRuleRegionNetworkFirewallPolicyRequest", "PatchRuleRegionSecurityPolicyRequest", "PatchRuleSecurityPolicyRequest", @@ -3143,6 +3207,12 @@ "PreservedStatePreservedDisk", "PreservedStatePreservedNetworkIp", "PreservedStatePreservedNetworkIpIpAddress", + "PreviewFeature", + "PreviewFeatureList", + "PreviewFeatureRolloutOperation", + "PreviewFeatureRolloutOperationRolloutInput", + "PreviewFeatureStatus", + "PreviewFeatureStatusReleaseStatus", "PreviewRouterRequest", "Project", "ProjectsDisableXpnResourceRequest", @@ -3207,6 +3277,7 @@ "RegionUrlMapsValidateRequest", "RemoveAssociationFirewallPolicyRequest", "RemoveAssociationNetworkFirewallPolicyRequest", + "RemoveAssociationOrganizationSecurityPolicyRequest", "RemoveAssociationRegionNetworkFirewallPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", @@ -3218,9 +3289,11 @@ "RemoveResourcePoliciesRegionDiskRequest", "RemoveRuleFirewallPolicyRequest", "RemoveRuleNetworkFirewallPolicyRequest", + "RemoveRuleOrganizationSecurityPolicyRequest", "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "ReportFaultyReservationSubBlockRequest", "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "RequestRemovePeeringNetworkRequest", @@ -3245,6 +3318,8 @@ "ReservationSubBlockPhysicalTopology", "ReservationSubBlocksGetResponse", "ReservationSubBlocksListResponse", + "ReservationSubBlocksReportFaultyRequest", + "ReservationSubBlocksReportFaultyRequestFaultReason", "ResetInstanceRequest", "ResizeDiskRequest", "ResizeInstanceGroupManagerRequest", @@ -3330,6 +3405,7 @@ "SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfigThresholdConfigTrafficGranularityConfig", "SecurityPolicyAdvancedOptionsConfig", "SecurityPolicyAdvancedOptionsConfigJsonCustomConfig", + "SecurityPolicyAssociation", "SecurityPolicyDdosProtectionConfig", "SecurityPolicyList", "SecurityPolicyRecaptchaOptionsConfig", @@ -3471,6 +3547,7 @@ "SimulateMaintenanceEventNodeGroupRequest", "Snapshot", "SnapshotList", + "SnapshotParams", "SnapshotSettings", "SnapshotSettingsStorageLocationSettings", "SnapshotSettingsStorageLocationSettingsStorageLocationPreference", @@ -3638,6 +3715,7 @@ "UpdatePeeringNetworkRequest", "UpdatePerInstanceConfigsInstanceGroupManagerRequest", "UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest", + "UpdatePreviewFeatureRequest", "UpdateRegionAutoscalerRequest", "UpdateRegionBackendServiceRequest", "UpdateRegionCommitmentRequest", 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 f65cf8b7b202..a535984f4fa9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -68,7 +68,9 @@ from .services.node_groups import NodeGroupsClient from .services.node_templates import NodeTemplatesClient from .services.node_types import NodeTypesClient +from .services.organization_security_policies import OrganizationSecurityPoliciesClient from .services.packet_mirrorings import PacketMirroringsClient +from .services.preview_features import PreviewFeaturesClient from .services.projects import ProjectsClient from .services.public_advertised_prefixes import PublicAdvertisedPrefixesClient from .services.public_delegated_prefixes import PublicDelegatedPrefixesClient @@ -140,6 +142,7 @@ AddAccessConfigInstanceRequest, AddAssociationFirewallPolicyRequest, AddAssociationNetworkFirewallPolicyRequest, + AddAssociationOrganizationSecurityPolicyRequest, AddAssociationRegionNetworkFirewallPolicyRequest, AddHealthCheckTargetPoolRequest, AddInstancesInstanceGroupRequest, @@ -157,6 +160,7 @@ AddressList, AddRuleFirewallPolicyRequest, AddRuleNetworkFirewallPolicyRequest, + AddRuleOrganizationSecurityPolicyRequest, AddRuleRegionNetworkFirewallPolicyRequest, AddRuleRegionSecurityPolicyRequest, AddRuleSecurityPolicyRequest, @@ -314,6 +318,7 @@ ConnectionDraining, ConsistentHashLoadBalancerSettings, ConsistentHashLoadBalancerSettingsHttpCookie, + CopyRulesOrganizationSecurityPolicyRequest, CorsPolicy, CreateInstancesInstanceGroupManagerRequest, CreateInstancesRegionInstanceGroupManagerRequest, @@ -325,6 +330,7 @@ CustomErrorResponsePolicy, CustomErrorResponsePolicyCustomErrorResponseRule, Data, + Date, DeleteAccessConfigInstanceRequest, DeleteAddressRequest, DeleteAutoscalerRequest, @@ -368,6 +374,7 @@ DeleteNodeGroupRequest, DeleteNodesNodeGroupRequest, DeleteNodeTemplateRequest, + DeleteOrganizationSecurityPolicyRequest, DeletePacketMirroringRequest, DeletePerInstanceConfigsInstanceGroupManagerRequest, DeletePerInstanceConfigsRegionInstanceGroupManagerRequest, @@ -491,6 +498,7 @@ GetAddressRequest, GetAssociationFirewallPolicyRequest, GetAssociationNetworkFirewallPolicyRequest, + GetAssociationOrganizationSecurityPolicyRequest, GetAssociationRegionNetworkFirewallPolicyRequest, GetAutoscalerRequest, GetBackendBucketRequest, @@ -501,6 +509,8 @@ GetEffectiveFirewallsInstanceRequest, GetEffectiveFirewallsNetworkRequest, GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest, + GetEffectiveSecurityPoliciesBackendServiceRequest, + GetEffectiveSecurityPoliciesBackendServiceResponse, GetExternalVpnGatewayRequest, GetFirewallPolicyRequest, GetFirewallRequest, @@ -576,8 +586,10 @@ GetNodeTypeRequest, GetOperationalStatusInterconnectAttachmentGroupRequest, GetOperationalStatusInterconnectGroupRequest, + GetOrganizationSecurityPolicyRequest, GetPacketMirroringRequest, GetPacketMirroringRuleNetworkFirewallPolicyRequest, + GetPreviewFeatureRequest, GetProjectRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, @@ -614,6 +626,7 @@ GetRouterStatusRouterRequest, GetRuleFirewallPolicyRequest, GetRuleNetworkFirewallPolicyRequest, + GetRuleOrganizationSecurityPolicyRequest, GetRuleRegionNetworkFirewallPolicyRequest, GetRuleRegionSecurityPolicyRequest, GetRuleSecurityPolicyRequest, @@ -689,6 +702,7 @@ Image, ImageFamilyView, ImageList, + ImageParams, InitialStateConfig, InsertAddressRequest, InsertAutoscalerRequest, @@ -724,6 +738,7 @@ InsertNetworkRequest, InsertNodeGroupRequest, InsertNodeTemplateRequest, + InsertOrganizationSecurityPolicyRequest, InsertPacketMirroringRequest, InsertPublicAdvertisedPrefixeRequest, InsertPublicDelegatedPrefixeRequest, @@ -939,6 +954,7 @@ ListAcceleratorTypesRequest, ListAddressesRequest, ListAssociationsFirewallPolicyRequest, + ListAssociationsOrganizationSecurityPolicyRequest, ListAutoscalersRequest, ListAvailableFeaturesRegionSslPoliciesRequest, ListAvailableFeaturesSslPoliciesRequest, @@ -993,11 +1009,14 @@ ListNodesNodeGroupsRequest, ListNodeTemplatesRequest, ListNodeTypesRequest, + ListOrganizationSecurityPoliciesRequest, ListPacketMirroringsRequest, ListPeeringRoutesNetworksRequest, ListPerInstanceConfigsInstanceGroupManagersRequest, ListPerInstanceConfigsRegionInstanceGroupManagersRequest, + ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, ListPreconfiguredExpressionSetsSecurityPoliciesRequest, + ListPreviewFeaturesRequest, ListPublicAdvertisedPrefixesRequest, ListPublicDelegatedPrefixesRequest, ListReferrersInstancesRequest, @@ -1082,6 +1101,7 @@ MoveFirewallPolicyRequest, MoveGlobalAddressRequest, MoveInstanceProjectRequest, + MoveOrganizationSecurityPolicyRequest, NamedPort, NatIpInfo, NatIpInfoNatIpInfoMapping, @@ -1159,6 +1179,7 @@ OperationAggregatedList, OperationList, OperationsScopedList, + OrganizationSecurityPoliciesListAssociationsResponse, OutlierDetection, PacketIntervals, PacketMirroring, @@ -1192,6 +1213,7 @@ PatchNetworkFirewallPolicyRequest, PatchNetworkRequest, PatchNodeGroupRequest, + PatchOrganizationSecurityPolicyRequest, PatchPacketMirroringRequest, PatchPacketMirroringRuleNetworkFirewallPolicyRequest, PatchPerInstanceConfigsInstanceGroupManagerRequest, @@ -1213,6 +1235,7 @@ PatchRouterRequest, PatchRuleFirewallPolicyRequest, PatchRuleNetworkFirewallPolicyRequest, + PatchRuleOrganizationSecurityPolicyRequest, PatchRuleRegionNetworkFirewallPolicyRequest, PatchRuleRegionSecurityPolicyRequest, PatchRuleSecurityPolicyRequest, @@ -1239,6 +1262,12 @@ PreservedStatePreservedDisk, PreservedStatePreservedNetworkIp, PreservedStatePreservedNetworkIpIpAddress, + PreviewFeature, + PreviewFeatureList, + PreviewFeatureRolloutOperation, + PreviewFeatureRolloutOperationRolloutInput, + PreviewFeatureStatus, + PreviewFeatureStatusReleaseStatus, PreviewRouterRequest, Project, ProjectsDisableXpnResourceRequest, @@ -1303,6 +1332,7 @@ RegionUrlMapsValidateRequest, RemoveAssociationFirewallPolicyRequest, RemoveAssociationNetworkFirewallPolicyRequest, + RemoveAssociationOrganizationSecurityPolicyRequest, RemoveAssociationRegionNetworkFirewallPolicyRequest, RemoveHealthCheckTargetPoolRequest, RemoveInstancesInstanceGroupRequest, @@ -1314,9 +1344,11 @@ RemoveResourcePoliciesRegionDiskRequest, RemoveRuleFirewallPolicyRequest, RemoveRuleNetworkFirewallPolicyRequest, + RemoveRuleOrganizationSecurityPolicyRequest, RemoveRuleRegionNetworkFirewallPolicyRequest, RemoveRuleRegionSecurityPolicyRequest, RemoveRuleSecurityPolicyRequest, + ReportFaultyReservationSubBlockRequest, ReportHostAsFaultyInstanceRequest, RequestMirrorPolicy, RequestRemovePeeringNetworkRequest, @@ -1341,6 +1373,8 @@ ReservationSubBlockPhysicalTopology, ReservationSubBlocksGetResponse, ReservationSubBlocksListResponse, + ReservationSubBlocksReportFaultyRequest, + ReservationSubBlocksReportFaultyRequestFaultReason, ResetInstanceRequest, ResizeDiskRequest, ResizeInstanceGroupManagerRequest, @@ -1426,6 +1460,7 @@ SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfigThresholdConfigTrafficGranularityConfig, SecurityPolicyAdvancedOptionsConfig, SecurityPolicyAdvancedOptionsConfigJsonCustomConfig, + SecurityPolicyAssociation, SecurityPolicyDdosProtectionConfig, SecurityPolicyList, SecurityPolicyRecaptchaOptionsConfig, @@ -1567,6 +1602,7 @@ SimulateMaintenanceEventNodeGroupRequest, Snapshot, SnapshotList, + SnapshotParams, SnapshotSettings, SnapshotSettingsStorageLocationSettings, SnapshotSettingsStorageLocationSettingsStorageLocationPreference, @@ -1734,6 +1770,7 @@ UpdatePeeringNetworkRequest, UpdatePerInstanceConfigsInstanceGroupManagerRequest, UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest, + UpdatePreviewFeatureRequest, UpdateRegionAutoscalerRequest, UpdateRegionBackendServiceRequest, UpdateRegionCommitmentRequest, @@ -1817,6 +1854,7 @@ "AddAccessConfigInstanceRequest", "AddAssociationFirewallPolicyRequest", "AddAssociationNetworkFirewallPolicyRequest", + "AddAssociationOrganizationSecurityPolicyRequest", "AddAssociationRegionNetworkFirewallPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstanceTargetPoolRequest", @@ -1830,6 +1868,7 @@ "AddResourcePoliciesRegionDiskRequest", "AddRuleFirewallPolicyRequest", "AddRuleNetworkFirewallPolicyRequest", + "AddRuleOrganizationSecurityPolicyRequest", "AddRuleRegionNetworkFirewallPolicyRequest", "AddRuleRegionSecurityPolicyRequest", "AddRuleSecurityPolicyRequest", @@ -1994,6 +2033,7 @@ "ConnectionDraining", "ConsistentHashLoadBalancerSettings", "ConsistentHashLoadBalancerSettingsHttpCookie", + "CopyRulesOrganizationSecurityPolicyRequest", "CorsPolicy", "CreateInstancesInstanceGroupManagerRequest", "CreateInstancesRegionInstanceGroupManagerRequest", @@ -2005,6 +2045,7 @@ "CustomerEncryptionKey", "CustomerEncryptionKeyProtectedDisk", "Data", + "Date", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -2048,6 +2089,7 @@ "DeleteNodeGroupRequest", "DeleteNodeTemplateRequest", "DeleteNodesNodeGroupRequest", + "DeleteOrganizationSecurityPolicyRequest", "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", @@ -2178,6 +2220,7 @@ "GetAddressRequest", "GetAssociationFirewallPolicyRequest", "GetAssociationNetworkFirewallPolicyRequest", + "GetAssociationOrganizationSecurityPolicyRequest", "GetAssociationRegionNetworkFirewallPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", @@ -2188,6 +2231,8 @@ "GetEffectiveFirewallsInstanceRequest", "GetEffectiveFirewallsNetworkRequest", "GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest", + "GetEffectiveSecurityPoliciesBackendServiceRequest", + "GetEffectiveSecurityPoliciesBackendServiceResponse", "GetExternalVpnGatewayRequest", "GetFirewallPolicyRequest", "GetFirewallRequest", @@ -2263,8 +2308,10 @@ "GetNodeTypeRequest", "GetOperationalStatusInterconnectAttachmentGroupRequest", "GetOperationalStatusInterconnectGroupRequest", + "GetOrganizationSecurityPolicyRequest", "GetPacketMirroringRequest", "GetPacketMirroringRuleNetworkFirewallPolicyRequest", + "GetPreviewFeatureRequest", "GetProjectRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", @@ -2301,6 +2348,7 @@ "GetRouterStatusRouterRequest", "GetRuleFirewallPolicyRequest", "GetRuleNetworkFirewallPolicyRequest", + "GetRuleOrganizationSecurityPolicyRequest", "GetRuleRegionNetworkFirewallPolicyRequest", "GetRuleRegionSecurityPolicyRequest", "GetRuleSecurityPolicyRequest", @@ -2383,6 +2431,7 @@ "ImageFamilyView", "ImageFamilyViewsClient", "ImageList", + "ImageParams", "ImagesClient", "InitialStateConfig", "InsertAddressRequest", @@ -2419,6 +2468,7 @@ "InsertNetworkRequest", "InsertNodeGroupRequest", "InsertNodeTemplateRequest", + "InsertOrganizationSecurityPolicyRequest", "InsertPacketMirroringRequest", "InsertPublicAdvertisedPrefixeRequest", "InsertPublicDelegatedPrefixeRequest", @@ -2649,6 +2699,7 @@ "ListAcceleratorTypesRequest", "ListAddressesRequest", "ListAssociationsFirewallPolicyRequest", + "ListAssociationsOrganizationSecurityPolicyRequest", "ListAutoscalersRequest", "ListAvailableFeaturesRegionSslPoliciesRequest", "ListAvailableFeaturesSslPoliciesRequest", @@ -2703,11 +2754,14 @@ "ListNodeTemplatesRequest", "ListNodeTypesRequest", "ListNodesNodeGroupsRequest", + "ListOrganizationSecurityPoliciesRequest", "ListPacketMirroringsRequest", "ListPeeringRoutesNetworksRequest", "ListPerInstanceConfigsInstanceGroupManagersRequest", "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", + "ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest", "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", + "ListPreviewFeaturesRequest", "ListPublicAdvertisedPrefixesRequest", "ListPublicDelegatedPrefixesRequest", "ListReferrersInstancesRequest", @@ -2794,6 +2848,7 @@ "MoveFirewallPolicyRequest", "MoveGlobalAddressRequest", "MoveInstanceProjectRequest", + "MoveOrganizationSecurityPolicyRequest", "NamedPort", "NatIpInfo", "NatIpInfoNatIpInfoMapping", @@ -2880,6 +2935,8 @@ "OperationAggregatedList", "OperationList", "OperationsScopedList", + "OrganizationSecurityPoliciesClient", + "OrganizationSecurityPoliciesListAssociationsResponse", "OutlierDetection", "PacketIntervals", "PacketMirroring", @@ -2914,6 +2971,7 @@ "PatchNetworkFirewallPolicyRequest", "PatchNetworkRequest", "PatchNodeGroupRequest", + "PatchOrganizationSecurityPolicyRequest", "PatchPacketMirroringRequest", "PatchPacketMirroringRuleNetworkFirewallPolicyRequest", "PatchPerInstanceConfigsInstanceGroupManagerRequest", @@ -2935,6 +2993,7 @@ "PatchRouterRequest", "PatchRuleFirewallPolicyRequest", "PatchRuleNetworkFirewallPolicyRequest", + "PatchRuleOrganizationSecurityPolicyRequest", "PatchRuleRegionNetworkFirewallPolicyRequest", "PatchRuleRegionSecurityPolicyRequest", "PatchRuleSecurityPolicyRequest", @@ -2961,6 +3020,13 @@ "PreservedStatePreservedDisk", "PreservedStatePreservedNetworkIp", "PreservedStatePreservedNetworkIpIpAddress", + "PreviewFeature", + "PreviewFeatureList", + "PreviewFeatureRolloutOperation", + "PreviewFeatureRolloutOperationRolloutInput", + "PreviewFeatureStatus", + "PreviewFeatureStatusReleaseStatus", + "PreviewFeaturesClient", "PreviewRouterRequest", "Project", "ProjectsClient", @@ -3053,6 +3119,7 @@ "RegionsClient", "RemoveAssociationFirewallPolicyRequest", "RemoveAssociationNetworkFirewallPolicyRequest", + "RemoveAssociationOrganizationSecurityPolicyRequest", "RemoveAssociationRegionNetworkFirewallPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstanceTargetPoolRequest", @@ -3064,9 +3131,11 @@ "RemoveResourcePoliciesRegionDiskRequest", "RemoveRuleFirewallPolicyRequest", "RemoveRuleNetworkFirewallPolicyRequest", + "RemoveRuleOrganizationSecurityPolicyRequest", "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "ReportFaultyReservationSubBlockRequest", "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "RequestRemovePeeringNetworkRequest", @@ -3089,6 +3158,8 @@ "ReservationSubBlocksClient", "ReservationSubBlocksGetResponse", "ReservationSubBlocksListResponse", + "ReservationSubBlocksReportFaultyRequest", + "ReservationSubBlocksReportFaultyRequestFaultReason", "ReservationsBlocksPerformMaintenanceRequest", "ReservationsClient", "ReservationsPerformMaintenanceRequest", @@ -3184,6 +3255,7 @@ "SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfigThresholdConfigTrafficGranularityConfig", "SecurityPolicyAdvancedOptionsConfig", "SecurityPolicyAdvancedOptionsConfigJsonCustomConfig", + "SecurityPolicyAssociation", "SecurityPolicyDdosProtectionConfig", "SecurityPolicyList", "SecurityPolicyRecaptchaOptionsConfig", @@ -3326,6 +3398,7 @@ "SimulateMaintenanceEventNodeGroupRequest", "Snapshot", "SnapshotList", + "SnapshotParams", "SnapshotSettings", "SnapshotSettingsServiceClient", "SnapshotSettingsStorageLocationSettings", @@ -3507,6 +3580,7 @@ "UpdatePeeringNetworkRequest", "UpdatePerInstanceConfigsInstanceGroupManagerRequest", "UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest", + "UpdatePreviewFeatureRequest", "UpdateRegionAutoscalerRequest", "UpdateRegionBackendServiceRequest", "UpdateRegionCommitmentRequest", 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 2efeb36f3997..894a0d959c06 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 @@ -221,6 +221,11 @@ "get" ] }, + "GetEffectiveSecurityPolicies": { + "methods": [ + "get_effective_security_policies" + ] + }, "GetHealth": { "methods": [ "get_health" @@ -2474,6 +2479,95 @@ } } }, + "OrganizationSecurityPolicies": { + "clients": { + "rest": { + "libraryClient": "OrganizationSecurityPoliciesClient", + "rpcs": { + "AddAssociation": { + "methods": [ + "add_association" + ] + }, + "AddRule": { + "methods": [ + "add_rule" + ] + }, + "CopyRules": { + "methods": [ + "copy_rules" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetAssociation": { + "methods": [ + "get_association" + ] + }, + "GetRule": { + "methods": [ + "get_rule" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "ListAssociations": { + "methods": [ + "list_associations" + ] + }, + "ListPreconfiguredExpressionSets": { + "methods": [ + "list_preconfigured_expression_sets" + ] + }, + "Move": { + "methods": [ + "move" + ] + }, + "Patch": { + "methods": [ + "patch" + ] + }, + "PatchRule": { + "methods": [ + "patch_rule" + ] + }, + "RemoveAssociation": { + "methods": [ + "remove_association" + ] + }, + "RemoveRule": { + "methods": [ + "remove_rule" + ] + } + } + } + } + }, "PacketMirrorings": { "clients": { "rest": { @@ -2518,6 +2612,30 @@ } } }, + "PreviewFeatures": { + "clients": { + "rest": { + "libraryClient": "PreviewFeaturesClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Update": { + "methods": [ + "update" + ] + } + } + } + } + }, "Projects": { "clients": { "rest": { @@ -3818,6 +3936,11 @@ "methods": [ "perform_maintenance" ] + }, + "ReportFaulty": { + "methods": [ + "report_faulty" + ] } } } diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py index e682b04f9c9a..3de2fd6431c5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py @@ -1825,6 +1825,137 @@ def sample_get(): # Done; return the response. return response + def get_effective_security_policies( + self, + request: Optional[ + Union[compute.GetEffectiveSecurityPoliciesBackendServiceRequest, dict] + ] = None, + *, + project: Optional[str] = None, + backend_service: 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.GetEffectiveSecurityPoliciesBackendServiceResponse: + r"""Returns effective security policies applied to this + backend service. + + .. 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_effective_security_policies(): + # Create a client + client = compute_v1.BackendServicesClient() + + # Initialize request argument(s) + request = compute_v1.GetEffectiveSecurityPoliciesBackendServiceRequest( + backend_service="backend_service_value", + project="project_value", + ) + + # Make the request + response = client.get_effective_security_policies(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetEffectiveSecurityPoliciesBackendServiceRequest, dict]): + The request object. A request message for + BackendServices.GetEffectiveSecurityPolicies. + 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. + backend_service (str): + Name of the Backend Service for this + request. + + This corresponds to the ``backend_service`` 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.GetEffectiveSecurityPoliciesBackendServiceResponse: + A response message for + BackendServices.GetEffectiveSecurityPolicies. + See the method description for details. + + """ + # 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, backend_service] + 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.GetEffectiveSecurityPoliciesBackendServiceRequest + ): + request = compute.GetEffectiveSecurityPoliciesBackendServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if backend_service is not None: + request.backend_service = backend_service + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_effective_security_policies + ] + + # 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), + ("backend_service", request.backend_service), + ) + ), + ) + + # 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 get_health( self, request: Optional[Union[compute.GetHealthBackendServiceRequest, dict]] = None, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/base.py index a3f52ca4a2a9..f8ca4669c99a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/base.py @@ -163,6 +163,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_effective_security_policies: gapic_v1.method.wrap_method( + self.get_effective_security_policies, + default_timeout=None, + client_info=client_info, + ), self.get_health: gapic_v1.method.wrap_method( self.get_health, default_timeout=None, @@ -277,6 +282,18 @@ def get( ]: raise NotImplementedError() + @property + def get_effective_security_policies( + self, + ) -> Callable[ + [compute.GetEffectiveSecurityPoliciesBackendServiceRequest], + Union[ + compute.GetEffectiveSecurityPoliciesBackendServiceResponse, + Awaitable[compute.GetEffectiveSecurityPoliciesBackendServiceResponse], + ], + ]: + raise NotImplementedError() + @property def get_health( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest.py index f98b41906cee..4316c7a87e9f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest.py @@ -112,6 +112,14 @@ def post_get(self, response): logging.log(f"Received response: {response}") return response + def pre_get_effective_security_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_effective_security_policies(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_health(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -445,6 +453,58 @@ def post_get_with_metadata( """ return response, metadata + def pre_get_effective_security_policies( + self, + request: compute.GetEffectiveSecurityPoliciesBackendServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetEffectiveSecurityPoliciesBackendServiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_effective_security_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackendServices server. + """ + return request, metadata + + def post_get_effective_security_policies( + self, response: compute.GetEffectiveSecurityPoliciesBackendServiceResponse + ) -> compute.GetEffectiveSecurityPoliciesBackendServiceResponse: + """Post-rpc interceptor for get_effective_security_policies + + DEPRECATED. Please use the `post_get_effective_security_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackendServices server but before + it is returned to user code. This `post_get_effective_security_policies` interceptor runs + before the `post_get_effective_security_policies_with_metadata` interceptor. + """ + return response + + def post_get_effective_security_policies_with_metadata( + self, + response: compute.GetEffectiveSecurityPoliciesBackendServiceResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetEffectiveSecurityPoliciesBackendServiceResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_effective_security_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackendServices server but before it is returned to user code. + + We recommend only using this `post_get_effective_security_policies_with_metadata` + interceptor in new development instead of the `post_get_effective_security_policies` interceptor. + When both interceptors are used, this `post_get_effective_security_policies_with_metadata` interceptor runs after the + `post_get_effective_security_policies` interceptor. The (possibly modified) response returned by + `post_get_effective_security_policies` will be passed to + `post_get_effective_security_policies_with_metadata`. + """ + return response, metadata + def pre_get_health( self, request: compute.GetHealthBackendServiceRequest, @@ -1882,6 +1942,166 @@ def __call__( ) return resp + class _GetEffectiveSecurityPolicies( + _BaseBackendServicesRestTransport._BaseGetEffectiveSecurityPolicies, + BackendServicesRestStub, + ): + def __hash__(self): + return hash("BackendServicesRestTransport.GetEffectiveSecurityPolicies") + + @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.GetEffectiveSecurityPoliciesBackendServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.GetEffectiveSecurityPoliciesBackendServiceResponse: + r"""Call the get effective security + policies method over HTTP. + + Args: + request (~.compute.GetEffectiveSecurityPoliciesBackendServiceRequest): + The request object. A request message for + BackendServices.GetEffectiveSecurityPolicies. + 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.GetEffectiveSecurityPoliciesBackendServiceResponse: + A response message for + BackendServices.GetEffectiveSecurityPolicies. + See the method description for details. + + """ + + http_options = ( + _BaseBackendServicesRestTransport._BaseGetEffectiveSecurityPolicies._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_effective_security_policies( + request, metadata + ) + transcoded_request = _BaseBackendServicesRestTransport._BaseGetEffectiveSecurityPolicies._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBackendServicesRestTransport._BaseGetEffectiveSecurityPolicies._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.BackendServicesClient.GetEffectiveSecurityPolicies", + extra={ + "serviceName": "google.cloud.compute.v1.BackendServices", + "rpcName": "GetEffectiveSecurityPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackendServicesRestTransport._GetEffectiveSecurityPolicies._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.GetEffectiveSecurityPoliciesBackendServiceResponse() + pb_resp = compute.GetEffectiveSecurityPoliciesBackendServiceResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_effective_security_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_get_effective_security_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.GetEffectiveSecurityPoliciesBackendServiceResponse.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.BackendServicesClient.get_effective_security_policies", + extra={ + "serviceName": "google.cloud.compute.v1.BackendServices", + "rpcName": "GetEffectiveSecurityPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GetHealth( _BaseBackendServicesRestTransport._BaseGetHealth, BackendServicesRestStub ): @@ -3743,6 +3963,17 @@ def get( # In C++ this would require a dynamic_cast return self._Get(self._session, self._host, self._interceptor) # type: ignore + @property + def get_effective_security_policies( + self, + ) -> Callable[ + [compute.GetEffectiveSecurityPoliciesBackendServiceRequest], + compute.GetEffectiveSecurityPoliciesBackendServiceResponse, + ]: + # 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._GetEffectiveSecurityPolicies(self._session, self._host, self._interceptor) # type: ignore + @property def get_health( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest_base.py index 4203ed913227..b1c8ef8a0a6b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest_base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/transports/rest_base.py @@ -329,6 +329,54 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseGetEffectiveSecurityPolicies: + 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/backendServices/{backend_service}/getEffectiveSecurityPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetEffectiveSecurityPoliciesBackendServiceRequest.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( + _BaseBackendServicesRestTransport._BaseGetEffectiveSecurityPolicies._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseGetHealth: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/__init__.py new file mode 100644 index 000000000000..941e6cb5be36 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 OrganizationSecurityPoliciesClient + +__all__ = ("OrganizationSecurityPoliciesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/client.py new file mode 100644 index 000000000000..90e0ef196df1 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/client.py @@ -0,0 +1,3947 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +import functools +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +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 +import google.protobuf + +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__) + +from google.api_core import extended_operation # type: ignore + +from google.cloud.compute_v1.services.organization_security_policies import pagers +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, OrganizationSecurityPoliciesTransport +from .transports.rest import OrganizationSecurityPoliciesRestTransport + + +class OrganizationSecurityPoliciesClientMeta(type): + """Metaclass for the OrganizationSecurityPolicies 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[OrganizationSecurityPoliciesTransport]] + _transport_registry["rest"] = OrganizationSecurityPoliciesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[OrganizationSecurityPoliciesTransport]: + """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 OrganizationSecurityPoliciesClient( + metaclass=OrganizationSecurityPoliciesClientMeta +): + """The OrganizationSecurityPolicies API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """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: + 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) + 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" + + @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: + OrganizationSecurityPoliciesClient: 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: + OrganizationSecurityPoliciesClient: 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) -> OrganizationSecurityPoliciesTransport: + """Returns the transport used by the client instance. + + Returns: + OrganizationSecurityPoliciesTransport: 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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true": + 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 = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true", 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 + ): + """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 = OrganizationSecurityPoliciesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = OrganizationSecurityPoliciesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + OrganizationSecurityPoliciesClient._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 = OrganizationSecurityPoliciesClient._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): + """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, + OrganizationSecurityPoliciesTransport, + Callable[..., OrganizationSecurityPoliciesTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the organization security 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,OrganizationSecurityPoliciesTransport,Callable[..., OrganizationSecurityPoliciesTransport]]]): + 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 OrganizationSecurityPoliciesTransport 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, + ) = OrganizationSecurityPoliciesClient._read_environment_variables() + self._client_cert_source = ( + OrganizationSecurityPoliciesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = OrganizationSecurityPoliciesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # 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, OrganizationSecurityPoliciesTransport + ) + if transport_provided: + # transport is a OrganizationSecurityPoliciesTransport 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(OrganizationSecurityPoliciesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or OrganizationSecurityPoliciesClient._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[OrganizationSecurityPoliciesTransport], + Callable[..., OrganizationSecurityPoliciesTransport], + ] = ( + OrganizationSecurityPoliciesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast( + Callable[..., OrganizationSecurityPoliciesTransport], 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.OrganizationSecurityPoliciesClient`.", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "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.OrganizationSecurityPolicies", + "credentialsType": None, + }, + ) + + def add_association_unary( + self, + request: Optional[ + Union[compute.AddAssociationOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy: Optional[str] = None, + security_policy_association_resource: Optional[ + compute.SecurityPolicyAssociation + ] = 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"""Inserts an association for the specified security + policy. This has billing implications. Projects in the + hierarchy with effective hierarchical security policies + will be automatically enrolled into Cloud Armor + Enterprise if not already enrolled. Use of this API to + modify firewall policies is deprecated. Use + firewallPolicies.addAssociation instead if possible. + + .. 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_add_association(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.AddAssociationOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.add_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.AddAssociationOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.AddAssociation. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_policy_association_resource (google.cloud.compute_v1.types.SecurityPolicyAssociation): + The body resource for this request + This corresponds to the ``security_policy_association_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 = [security_policy, security_policy_association_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.AddAssociationOrganizationSecurityPolicyRequest + ): + request = compute.AddAssociationOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + if security_policy_association_resource is not None: + request.security_policy_association_resource = ( + security_policy_association_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_association] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 add_association( + self, + request: Optional[ + Union[compute.AddAssociationOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy: Optional[str] = None, + security_policy_association_resource: Optional[ + compute.SecurityPolicyAssociation + ] = 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"""Inserts an association for the specified security + policy. This has billing implications. Projects in the + hierarchy with effective hierarchical security policies + will be automatically enrolled into Cloud Armor + Enterprise if not already enrolled. Use of this API to + modify firewall policies is deprecated. Use + firewallPolicies.addAssociation instead if possible. + + .. 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_add_association(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.AddAssociationOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.add_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.AddAssociationOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.AddAssociation. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_policy_association_resource (google.cloud.compute_v1.types.SecurityPolicyAssociation): + The body resource for this request + This corresponds to the ``security_policy_association_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 = [security_policy, security_policy_association_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.AddAssociationOrganizationSecurityPolicyRequest + ): + request = compute.AddAssociationOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + if security_policy_association_resource is not None: + request.security_policy_association_resource = ( + security_policy_association_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_association] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + 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 add_rule_unary( + self, + request: Optional[ + Union[compute.AddRuleOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy: Optional[str] = None, + security_policy_rule_resource: Optional[compute.SecurityPolicyRule] = 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"""Inserts a rule into a security 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_add_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.AddRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.add_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.AddRuleOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.AddRule. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_policy_rule_resource (google.cloud.compute_v1.types.SecurityPolicyRule): + The body resource for this request + This corresponds to the ``security_policy_rule_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 = [security_policy, security_policy_rule_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.AddRuleOrganizationSecurityPolicyRequest): + request = compute.AddRuleOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + if security_policy_rule_resource is not None: + request.security_policy_rule_resource = security_policy_rule_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 add_rule( + self, + request: Optional[ + Union[compute.AddRuleOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy: Optional[str] = None, + security_policy_rule_resource: Optional[compute.SecurityPolicyRule] = 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"""Inserts a rule into a security 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_add_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.AddRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.add_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.AddRuleOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.AddRule. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_policy_rule_resource (google.cloud.compute_v1.types.SecurityPolicyRule): + The body resource for this request + This corresponds to the ``security_policy_rule_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 = [security_policy, security_policy_rule_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.AddRuleOrganizationSecurityPolicyRequest): + request = compute.AddRuleOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + if security_policy_rule_resource is not None: + request.security_policy_rule_resource = security_policy_rule_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + 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 copy_rules_unary( + self, + request: Optional[ + Union[compute.CopyRulesOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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.Operation: + r"""Copies rules to the specified security policy. Use of + this API to modify firewall policies is deprecated. Use + firewallPolicies.copyRules instead. + + .. 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_copy_rules(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.CopyRulesOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.copy_rules(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CopyRulesOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.CopyRules. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_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.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 = [security_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.CopyRulesOrganizationSecurityPolicyRequest): + request = compute.CopyRulesOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.copy_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 copy_rules( + self, + request: Optional[ + Union[compute.CopyRulesOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Copies rules to the specified security policy. Use of + this API to modify firewall policies is deprecated. Use + firewallPolicies.copyRules instead. + + .. 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_copy_rules(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.CopyRulesOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.copy_rules(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.CopyRulesOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.CopyRules. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_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.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 = [security_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.CopyRulesOrganizationSecurityPolicyRequest): + request = compute.CopyRulesOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.copy_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + 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.DeleteOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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.Operation: + r"""Deletes the specified policy. Use of this API to + remove firewall policies is deprecated. Use + firewallPolicies.delete instead. + + .. 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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.DeleteOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Delete. See + the method description for details. + security_policy (str): + Name of the security policy to + delete. + + This corresponds to the ``security_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.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 = [security_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.DeleteOrganizationSecurityPolicyRequest): + request = compute.DeleteOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # 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( + (("security_policy", request.security_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.DeleteOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes the specified policy. Use of this API to + remove firewall policies is deprecated. Use + firewallPolicies.delete instead. + + .. 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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.DeleteOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Delete. See + the method description for details. + security_policy (str): + Name of the security policy to + delete. + + This corresponds to the ``security_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.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 = [security_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.DeleteOrganizationSecurityPolicyRequest): + request = compute.DeleteOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # 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( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + 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.GetOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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.SecurityPolicy: + r"""List all of the ordered rules present in a single + specified policy. Use of this API to read firewall + policies is deprecated. Use firewallPolicies.get + instead. + + .. 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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.GetOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Get. See + the method description for details. + security_policy (str): + Name of the security policy to get. + This corresponds to the ``security_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.SecurityPolicy: + Represents a Google Cloud Armor + security policy resource. Only external + backend services that use load balancers + can reference a security policy. For + more information, see Google Cloud Armor + security policy overview. + + """ + # 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 = [security_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.GetOrganizationSecurityPolicyRequest): + request = compute.GetOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_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( + (("security_policy", request.security_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 get_association( + self, + request: Optional[ + Union[compute.GetAssociationOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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.SecurityPolicyAssociation: + r"""Gets an association with the specified name. Use of + this API to read firewall policies is deprecated. Use + firewallPolicies.getAssociation instead if possible. + + .. 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_association(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.GetAssociationOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.get_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetAssociationOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.GetAssociation. + See the method description for details. + security_policy (str): + Name of the security policy to which + the queried rule belongs. + + This corresponds to the ``security_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.SecurityPolicyAssociation: + + """ + # 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 = [security_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.GetAssociationOrganizationSecurityPolicyRequest + ): + request = compute.GetAssociationOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_association] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 get_rule( + self, + request: Optional[ + Union[compute.GetRuleOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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.SecurityPolicyRule: + r"""Gets a rule at the specified priority. Use of this + API to read firewall policies is deprecated. Use + firewallPolicies.getRule instead. + + .. 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_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.GetRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.get_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetRuleOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.GetRule. + See the method description for details. + security_policy (str): + Name of the security policy to which + the queried rule belongs. + + This corresponds to the ``security_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.SecurityPolicyRule: + Represents a rule that describes one + or more match conditions along with the + action to be taken when traffic matches + this condition (allow or deny). + + """ + # 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 = [security_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.GetRuleOrganizationSecurityPolicyRequest): + request = compute.GetRuleOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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.InsertOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy_resource: Optional[compute.SecurityPolicy] = 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 policy in the specified project using + the data included in the request. Use of this API to + insert firewall policies is deprecated. Use + firewallPolicies.insert instead. + + .. 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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.InsertOrganizationSecurityPolicyRequest( + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Insert. See + the method description for details. + security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): + The body resource for this request + This corresponds to the ``security_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 = [security_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.InsertOrganizationSecurityPolicyRequest): + request = compute.InsertOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy_resource is not None: + request.security_policy_resource = security_policy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # 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.InsertOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy_resource: Optional[compute.SecurityPolicy] = 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 policy in the specified project using + the data included in the request. Use of this API to + insert firewall policies is deprecated. Use + firewallPolicies.insert instead. + + .. 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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.InsertOrganizationSecurityPolicyRequest( + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Insert. See + the method description for details. + security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): + The body resource for this request + This corresponds to the ``security_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 = [security_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.InsertOrganizationSecurityPolicyRequest): + request = compute.InsertOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy_resource is not None: + request.security_policy_resource = security_policy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # 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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.parent_id = request.parent_id + 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.ListOrganizationSecurityPoliciesRequest, dict] + ] = 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"""List all the policies that have been configured for + the specified project. Use of this API to read firewall + policies is deprecated. Use firewallPolicies.list + instead. + + .. 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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.ListOrganizationSecurityPoliciesRequest( + ) + + # 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.ListOrganizationSecurityPoliciesRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.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: + google.cloud.compute_v1.services.organization_security_policies.pagers.ListPager: + 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, compute.ListOrganizationSecurityPoliciesRequest): + request = compute.ListOrganizationSecurityPoliciesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # 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 list_associations( + self, + request: Optional[ + Union[compute.ListAssociationsOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.OrganizationSecurityPoliciesListAssociationsResponse: + r"""Lists associations of a specified target, i.e., + organization or folder. Use of this API to read firewall + policies is deprecated. Use + firewallPolicies.listAssociations instead if possible. + + .. 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_associations(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.ListAssociationsOrganizationSecurityPolicyRequest( + ) + + # Make the request + response = client.list_associations(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListAssociationsOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.ListAssociations. + 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: + google.cloud.compute_v1.types.OrganizationSecurityPoliciesListAssociationsResponse: + + """ + # 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, compute.ListAssociationsOrganizationSecurityPolicyRequest + ): + request = compute.ListAssociationsOrganizationSecurityPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_associations] + + # 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_preconfigured_expression_sets( + self, + request: Optional[ + Union[ + compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, + dict, + ] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse: + r"""Gets the current list of preconfigured Web + Application Firewall (WAF) expressions. + + .. 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_preconfigured_expression_sets(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest( + ) + + # Make the request + response = client.list_preconfigured_expression_sets(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.ListPreconfiguredExpressionSets. + 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: + google.cloud.compute_v1.types.SecurityPoliciesListPreconfiguredExpressionSetsResponse: + + """ + # 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, + compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, + ): + request = compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_preconfigured_expression_sets + ] + + # 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 move_unary( + self, + request: Optional[ + Union[compute.MoveOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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.Operation: + r"""Moves the specified security policy. Use of this API + to modify firewall policies is deprecated. Use + firewallPolicies.move instead. + + .. 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_move(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.MoveOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.move(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.MoveOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Move. See + the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_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.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 = [security_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.MoveOrganizationSecurityPolicyRequest): + request = compute.MoveOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.move] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 move( + self, + request: Optional[ + Union[compute.MoveOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Moves the specified security policy. Use of this API + to modify firewall policies is deprecated. Use + firewallPolicies.move instead. + + .. 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_move(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.MoveOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.move(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.MoveOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Move. See + the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_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.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 = [security_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.MoveOrganizationSecurityPolicyRequest): + request = compute.MoveOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.move] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.parent_id = request.parent_id + 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 patch_unary( + self, + request: Optional[ + Union[compute.PatchOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy: Optional[str] = None, + security_policy_resource: Optional[compute.SecurityPolicy] = 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"""Patches the specified policy with the data included + in the request. Use of this API to modify firewall + policies is deprecated. Use firewallPolicies.patch + instead. + + .. 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_patch(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.PatchOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.PatchOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Patch. See + the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): + The body resource for this request + This corresponds to the ``security_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 = [security_policy, security_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.PatchOrganizationSecurityPolicyRequest): + request = compute.PatchOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + if security_policy_resource is not None: + request.security_policy_resource = security_policy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 patch( + self, + request: Optional[ + Union[compute.PatchOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy: Optional[str] = None, + security_policy_resource: Optional[compute.SecurityPolicy] = 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"""Patches the specified policy with the data included + in the request. Use of this API to modify firewall + policies is deprecated. Use firewallPolicies.patch + instead. + + .. 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_patch(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.PatchOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.PatchOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.Patch. See + the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): + The body resource for this request + This corresponds to the ``security_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 = [security_policy, security_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.PatchOrganizationSecurityPolicyRequest): + request = compute.PatchOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + if security_policy_resource is not None: + request.security_policy_resource = security_policy_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + 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 patch_rule_unary( + self, + request: Optional[ + Union[compute.PatchRuleOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy: Optional[str] = None, + security_policy_rule_resource: Optional[compute.SecurityPolicyRule] = 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"""Patches a rule at the specified priority. Use of this + API to modify firewall policies is deprecated. Use + firewallPolicies.patchRule instead. + + .. 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_patch_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.PatchRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.patch_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.PatchRuleOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.PatchRule. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_policy_rule_resource (google.cloud.compute_v1.types.SecurityPolicyRule): + The body resource for this request + This corresponds to the ``security_policy_rule_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 = [security_policy, security_policy_rule_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.PatchRuleOrganizationSecurityPolicyRequest): + request = compute.PatchRuleOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + if security_policy_rule_resource is not None: + request.security_policy_rule_resource = security_policy_rule_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 patch_rule( + self, + request: Optional[ + Union[compute.PatchRuleOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_policy: Optional[str] = None, + security_policy_rule_resource: Optional[compute.SecurityPolicyRule] = 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"""Patches a rule at the specified priority. Use of this + API to modify firewall policies is deprecated. Use + firewallPolicies.patchRule instead. + + .. 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_patch_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.PatchRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.patch_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.PatchRuleOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.PatchRule. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_policy_rule_resource (google.cloud.compute_v1.types.SecurityPolicyRule): + The body resource for this request + This corresponds to the ``security_policy_rule_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 = [security_policy, security_policy_rule_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.PatchRuleOrganizationSecurityPolicyRequest): + request = compute.PatchRuleOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + if security_policy_rule_resource is not None: + request.security_policy_rule_resource = security_policy_rule_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + 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 remove_association_unary( + self, + request: Optional[ + Union[compute.RemoveAssociationOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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.Operation: + r"""Removes an association for the specified security + policy. Use of this API to modify firewall policies is + deprecated. Use firewallPolicies.removeAssociation + instead if possible. + + .. 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_remove_association(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.RemoveAssociationOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.remove_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.RemoveAssociationOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.RemoveAssociation. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_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.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 = [security_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.RemoveAssociationOrganizationSecurityPolicyRequest + ): + request = compute.RemoveAssociationOrganizationSecurityPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_association] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 remove_association( + self, + request: Optional[ + Union[compute.RemoveAssociationOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Removes an association for the specified security + policy. Use of this API to modify firewall policies is + deprecated. Use firewallPolicies.removeAssociation + instead if possible. + + .. 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_remove_association(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.RemoveAssociationOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.remove_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.RemoveAssociationOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.RemoveAssociation. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_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.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 = [security_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.RemoveAssociationOrganizationSecurityPolicyRequest + ): + request = compute.RemoveAssociationOrganizationSecurityPolicyRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_association] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + 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 remove_rule_unary( + self, + request: Optional[ + Union[compute.RemoveRuleOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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.Operation: + r"""Deletes a rule at the specified priority. + + .. 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_remove_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.RemoveRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.remove_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.RemoveRuleOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.RemoveRule. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_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.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 = [security_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.RemoveRuleOrganizationSecurityPolicyRequest): + request = compute.RemoveRuleOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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 remove_rule( + self, + request: Optional[ + Union[compute.RemoveRuleOrganizationSecurityPolicyRequest, dict] + ] = None, + *, + security_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]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes a rule at the specified priority. + + .. 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_remove_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.RemoveRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.remove_rule(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.RemoveRuleOrganizationSecurityPolicyRequest, dict]): + The request object. A request message for + OrganizationSecurityPolicies.RemoveRule. + See the method description for details. + security_policy (str): + Name of the security policy to + update. + + This corresponds to the ``security_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.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 = [security_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.RemoveRuleOrganizationSecurityPolicyRequest): + request = compute.RemoveRuleOrganizationSecurityPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_policy is not None: + request.security_policy = security_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_policy", request.security_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_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + 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) -> "OrganizationSecurityPoliciesClient": + 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__ = ("OrganizationSecurityPoliciesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/pagers.py new file mode 100644 index 000000000000..f888dbb5e196 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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.SecurityPolicyList` 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.SecurityPolicyList` + 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.SecurityPolicyList], + request: compute.ListOrganizationSecurityPoliciesRequest, + response: compute.SecurityPolicyList, + *, + 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.ListOrganizationSecurityPoliciesRequest): + The initial request object. + response (google.cloud.compute_v1.types.SecurityPolicyList): + 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.ListOrganizationSecurityPoliciesRequest(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.SecurityPolicyList]: + 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.SecurityPolicy]: + 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/organization_security_policies/transports/README.rst b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/README.rst new file mode 100644 index 000000000000..1985deee532e --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`OrganizationSecurityPoliciesTransport` is the ABC for all transports. +- public child `OrganizationSecurityPoliciesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `OrganizationSecurityPoliciesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseOrganizationSecurityPoliciesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `OrganizationSecurityPoliciesRestTransport` 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/organization_security_policies/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/__init__.py new file mode 100644 index 000000000000..4ea5804aaf22 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 OrganizationSecurityPoliciesTransport +from .rest import ( + OrganizationSecurityPoliciesRestInterceptor, + OrganizationSecurityPoliciesRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[OrganizationSecurityPoliciesTransport]] +_transport_registry["rest"] = OrganizationSecurityPoliciesRestTransport + +__all__ = ( + "OrganizationSecurityPoliciesTransport", + "OrganizationSecurityPoliciesRestTransport", + "OrganizationSecurityPoliciesRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/base.py new file mode 100644 index 000000000000..03245db1417c --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/base.py @@ -0,0 +1,410 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.services import global_organization_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 OrganizationSecurityPoliciesTransport(abc.ABC): + """Abstract transport class for OrganizationSecurityPolicies.""" + + 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. + """ + self._extended_operations_services: Dict[str, Any] = {} + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # 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_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # 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 + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.add_association: gapic_v1.method.wrap_method( + self.add_association, + default_timeout=None, + client_info=client_info, + ), + self.add_rule: gapic_v1.method.wrap_method( + self.add_rule, + default_timeout=None, + client_info=client_info, + ), + self.copy_rules: gapic_v1.method.wrap_method( + self.copy_rules, + default_timeout=None, + client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=None, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_timeout=None, + client_info=client_info, + ), + self.get_association: gapic_v1.method.wrap_method( + self.get_association, + default_timeout=None, + client_info=client_info, + ), + self.get_rule: gapic_v1.method.wrap_method( + self.get_rule, + default_timeout=None, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=None, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_timeout=None, + client_info=client_info, + ), + self.list_associations: gapic_v1.method.wrap_method( + self.list_associations, + default_timeout=None, + client_info=client_info, + ), + self.list_preconfigured_expression_sets: gapic_v1.method.wrap_method( + self.list_preconfigured_expression_sets, + default_timeout=None, + client_info=client_info, + ), + self.move: gapic_v1.method.wrap_method( + self.move, + default_timeout=None, + client_info=client_info, + ), + self.patch: gapic_v1.method.wrap_method( + self.patch, + default_timeout=None, + client_info=client_info, + ), + self.patch_rule: gapic_v1.method.wrap_method( + self.patch_rule, + default_timeout=None, + client_info=client_info, + ), + self.remove_association: gapic_v1.method.wrap_method( + self.remove_association, + default_timeout=None, + client_info=client_info, + ), + self.remove_rule: gapic_v1.method.wrap_method( + self.remove_rule, + default_timeout=None, + 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 add_association( + self, + ) -> Callable[ + [compute.AddAssociationOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def add_rule( + self, + ) -> Callable[ + [compute.AddRuleOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def copy_rules( + self, + ) -> Callable[ + [compute.CopyRulesOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetOrganizationSecurityPolicyRequest], + Union[compute.SecurityPolicy, Awaitable[compute.SecurityPolicy]], + ]: + raise NotImplementedError() + + @property + def get_association( + self, + ) -> Callable[ + [compute.GetAssociationOrganizationSecurityPolicyRequest], + Union[ + compute.SecurityPolicyAssociation, + Awaitable[compute.SecurityPolicyAssociation], + ], + ]: + raise NotImplementedError() + + @property + def get_rule( + self, + ) -> Callable[ + [compute.GetRuleOrganizationSecurityPolicyRequest], + Union[compute.SecurityPolicyRule, Awaitable[compute.SecurityPolicyRule]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListOrganizationSecurityPoliciesRequest], + Union[compute.SecurityPolicyList, Awaitable[compute.SecurityPolicyList]], + ]: + raise NotImplementedError() + + @property + def list_associations( + self, + ) -> Callable[ + [compute.ListAssociationsOrganizationSecurityPolicyRequest], + Union[ + compute.OrganizationSecurityPoliciesListAssociationsResponse, + Awaitable[compute.OrganizationSecurityPoliciesListAssociationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_preconfigured_expression_sets( + self, + ) -> Callable[ + [compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest], + Union[ + compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse, + Awaitable[compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def move( + self, + ) -> Callable[ + [compute.MoveOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def patch( + self, + ) -> Callable[ + [compute.PatchOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def patch_rule( + self, + ) -> Callable[ + [compute.PatchRuleOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def remove_association( + self, + ) -> Callable[ + [compute.RemoveAssociationOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def remove_rule( + self, + ) -> Callable[ + [compute.RemoveRuleOrganizationSecurityPolicyRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _global_organization_operations_client( + self, + ) -> global_organization_operations.GlobalOrganizationOperationsClient: + ex_op_service = self._extended_operations_services.get( + "global_organization_operations" + ) + if not ex_op_service: + ex_op_service = ( + global_organization_operations.GlobalOrganizationOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + ) + self._extended_operations_services[ + "global_organization_operations" + ] = ex_op_service + + return ex_op_service + + +__all__ = ("OrganizationSecurityPoliciesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/rest.py new file mode 100644 index 000000000000..f579091bcca2 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/rest.py @@ -0,0 +1,3827 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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 +import google.protobuf +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 _BaseOrganizationSecurityPoliciesRestTransport + +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 OrganizationSecurityPoliciesRestInterceptor: + """Interceptor for OrganizationSecurityPolicies. + + 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 OrganizationSecurityPoliciesRestTransport. + + .. code-block:: python + class MyCustomOrganizationSecurityPoliciesInterceptor(OrganizationSecurityPoliciesRestInterceptor): + def pre_add_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_add_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_copy_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_copy_rules(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_get_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_rule(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_list_associations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_associations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_preconfigured_expression_sets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_preconfigured_expression_sets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_move(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_move(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_patch(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_patch(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_patch_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_patch_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_rule(self, response): + logging.log(f"Received response: {response}") + return response + + transport = OrganizationSecurityPoliciesRestTransport(interceptor=MyCustomOrganizationSecurityPoliciesInterceptor()) + client = OrganizationSecurityPoliciesClient(transport=transport) + + + """ + + def pre_add_association( + self, + request: compute.AddAssociationOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.AddAssociationOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for add_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_add_association(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for add_association + + DEPRECATED. Please use the `post_add_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_add_association` interceptor runs + before the `post_add_association_with_metadata` interceptor. + """ + return response + + def post_add_association_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 add_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_add_association_with_metadata` + interceptor in new development instead of the `post_add_association` interceptor. + When both interceptors are used, this `post_add_association_with_metadata` interceptor runs after the + `post_add_association` interceptor. The (possibly modified) response returned by + `post_add_association` will be passed to + `post_add_association_with_metadata`. + """ + return response, metadata + + def pre_add_rule( + self, + request: compute.AddRuleOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.AddRuleOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for add_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_add_rule(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for add_rule + + DEPRECATED. Please use the `post_add_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_add_rule` interceptor runs + before the `post_add_rule_with_metadata` interceptor. + """ + return response + + def post_add_rule_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 add_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_add_rule_with_metadata` + interceptor in new development instead of the `post_add_rule` interceptor. + When both interceptors are used, this `post_add_rule_with_metadata` interceptor runs after the + `post_add_rule` interceptor. The (possibly modified) response returned by + `post_add_rule` will be passed to + `post_add_rule_with_metadata`. + """ + return response, metadata + + def pre_copy_rules( + self, + request: compute.CopyRulesOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CopyRulesOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for copy_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_copy_rules(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for copy_rules + + DEPRECATED. Please use the `post_copy_rules_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_copy_rules` interceptor runs + before the `post_copy_rules_with_metadata` interceptor. + """ + return response + + def post_copy_rules_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 copy_rules + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_copy_rules_with_metadata` + interceptor in new development instead of the `post_copy_rules` interceptor. + When both interceptors are used, this `post_copy_rules_with_metadata` interceptor runs after the + `post_copy_rules` interceptor. The (possibly modified) response returned by + `post_copy_rules` will be passed to + `post_copy_rules_with_metadata`. + """ + return response, metadata + + def pre_delete( + self, + request: compute.DeleteOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.DeleteOrganizationSecurityPolicyRequest, + 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 OrganizationSecurityPolicies 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 OrganizationSecurityPolicies 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 OrganizationSecurityPolicies 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.GetOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetOrganizationSecurityPolicyRequest, + 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 OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_get(self, response: compute.SecurityPolicy) -> compute.SecurityPolicy: + """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 OrganizationSecurityPolicies 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.SecurityPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.SecurityPolicy, 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 OrganizationSecurityPolicies 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_get_association( + self, + request: compute.GetAssociationOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetAssociationOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_get_association( + self, response: compute.SecurityPolicyAssociation + ) -> compute.SecurityPolicyAssociation: + """Post-rpc interceptor for get_association + + DEPRECATED. Please use the `post_get_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_get_association` interceptor runs + before the `post_get_association_with_metadata` interceptor. + """ + return response + + def post_get_association_with_metadata( + self, + response: compute.SecurityPolicyAssociation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.SecurityPolicyAssociation, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_get_association_with_metadata` + interceptor in new development instead of the `post_get_association` interceptor. + When both interceptors are used, this `post_get_association_with_metadata` interceptor runs after the + `post_get_association` interceptor. The (possibly modified) response returned by + `post_get_association` will be passed to + `post_get_association_with_metadata`. + """ + return response, metadata + + def pre_get_rule( + self, + request: compute.GetRuleOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetRuleOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_get_rule( + self, response: compute.SecurityPolicyRule + ) -> compute.SecurityPolicyRule: + """Post-rpc interceptor for get_rule + + DEPRECATED. Please use the `post_get_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_get_rule` interceptor runs + before the `post_get_rule_with_metadata` interceptor. + """ + return response + + def post_get_rule_with_metadata( + self, + response: compute.SecurityPolicyRule, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.SecurityPolicyRule, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_get_rule_with_metadata` + interceptor in new development instead of the `post_get_rule` interceptor. + When both interceptors are used, this `post_get_rule_with_metadata` interceptor runs after the + `post_get_rule` interceptor. The (possibly modified) response returned by + `post_get_rule` will be passed to + `post_get_rule_with_metadata`. + """ + return response, metadata + + def pre_insert( + self, + request: compute.InsertOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.InsertOrganizationSecurityPolicyRequest, + 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 OrganizationSecurityPolicies 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 OrganizationSecurityPolicies 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 OrganizationSecurityPolicies 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.ListOrganizationSecurityPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListOrganizationSecurityPoliciesRequest, + 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 OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_list( + self, response: compute.SecurityPolicyList + ) -> compute.SecurityPolicyList: + """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 OrganizationSecurityPolicies 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.SecurityPolicyList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.SecurityPolicyList, 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 OrganizationSecurityPolicies 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_list_associations( + self, + request: compute.ListAssociationsOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListAssociationsOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_associations + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_list_associations( + self, response: compute.OrganizationSecurityPoliciesListAssociationsResponse + ) -> compute.OrganizationSecurityPoliciesListAssociationsResponse: + """Post-rpc interceptor for list_associations + + DEPRECATED. Please use the `post_list_associations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_list_associations` interceptor runs + before the `post_list_associations_with_metadata` interceptor. + """ + return response + + def post_list_associations_with_metadata( + self, + response: compute.OrganizationSecurityPoliciesListAssociationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.OrganizationSecurityPoliciesListAssociationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_associations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_list_associations_with_metadata` + interceptor in new development instead of the `post_list_associations` interceptor. + When both interceptors are used, this `post_list_associations_with_metadata` interceptor runs after the + `post_list_associations` interceptor. The (possibly modified) response returned by + `post_list_associations` will be passed to + `post_list_associations_with_metadata`. + """ + return response, metadata + + def pre_list_preconfigured_expression_sets( + self, + request: compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_preconfigured_expression_sets + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_list_preconfigured_expression_sets( + self, response: compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse + ) -> compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse: + """Post-rpc interceptor for list_preconfigured_expression_sets + + DEPRECATED. Please use the `post_list_preconfigured_expression_sets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_list_preconfigured_expression_sets` interceptor runs + before the `post_list_preconfigured_expression_sets_with_metadata` interceptor. + """ + return response + + def post_list_preconfigured_expression_sets_with_metadata( + self, + response: compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_preconfigured_expression_sets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_list_preconfigured_expression_sets_with_metadata` + interceptor in new development instead of the `post_list_preconfigured_expression_sets` interceptor. + When both interceptors are used, this `post_list_preconfigured_expression_sets_with_metadata` interceptor runs after the + `post_list_preconfigured_expression_sets` interceptor. The (possibly modified) response returned by + `post_list_preconfigured_expression_sets` will be passed to + `post_list_preconfigured_expression_sets_with_metadata`. + """ + return response, metadata + + def pre_move( + self, + request: compute.MoveOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.MoveOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for move + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_move(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for move + + DEPRECATED. Please use the `post_move_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_move` interceptor runs + before the `post_move_with_metadata` interceptor. + """ + return response + + def post_move_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 move + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_move_with_metadata` + interceptor in new development instead of the `post_move` interceptor. + When both interceptors are used, this `post_move_with_metadata` interceptor runs after the + `post_move` interceptor. The (possibly modified) response returned by + `post_move` will be passed to + `post_move_with_metadata`. + """ + return response, metadata + + def pre_patch( + self, + request: compute.PatchOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.PatchOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for patch + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_patch(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for patch + + DEPRECATED. Please use the `post_patch_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_patch` interceptor runs + before the `post_patch_with_metadata` interceptor. + """ + return response + + def post_patch_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 patch + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_patch_with_metadata` + interceptor in new development instead of the `post_patch` interceptor. + When both interceptors are used, this `post_patch_with_metadata` interceptor runs after the + `post_patch` interceptor. The (possibly modified) response returned by + `post_patch` will be passed to + `post_patch_with_metadata`. + """ + return response, metadata + + def pre_patch_rule( + self, + request: compute.PatchRuleOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.PatchRuleOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for patch_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_patch_rule(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for patch_rule + + DEPRECATED. Please use the `post_patch_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_patch_rule` interceptor runs + before the `post_patch_rule_with_metadata` interceptor. + """ + return response + + def post_patch_rule_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 patch_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_patch_rule_with_metadata` + interceptor in new development instead of the `post_patch_rule` interceptor. + When both interceptors are used, this `post_patch_rule_with_metadata` interceptor runs after the + `post_patch_rule` interceptor. The (possibly modified) response returned by + `post_patch_rule` will be passed to + `post_patch_rule_with_metadata`. + """ + return response, metadata + + def pre_remove_association( + self, + request: compute.RemoveAssociationOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.RemoveAssociationOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for remove_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_remove_association(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for remove_association + + DEPRECATED. Please use the `post_remove_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_remove_association` interceptor runs + before the `post_remove_association_with_metadata` interceptor. + """ + return response + + def post_remove_association_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 remove_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_remove_association_with_metadata` + interceptor in new development instead of the `post_remove_association` interceptor. + When both interceptors are used, this `post_remove_association_with_metadata` interceptor runs after the + `post_remove_association` interceptor. The (possibly modified) response returned by + `post_remove_association` will be passed to + `post_remove_association_with_metadata`. + """ + return response, metadata + + def pre_remove_rule( + self, + request: compute.RemoveRuleOrganizationSecurityPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.RemoveRuleOrganizationSecurityPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for remove_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationSecurityPolicies server. + """ + return request, metadata + + def post_remove_rule(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for remove_rule + + DEPRECATED. Please use the `post_remove_rule_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationSecurityPolicies server but before + it is returned to user code. This `post_remove_rule` interceptor runs + before the `post_remove_rule_with_metadata` interceptor. + """ + return response + + def post_remove_rule_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 remove_rule + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationSecurityPolicies server but before it is returned to user code. + + We recommend only using this `post_remove_rule_with_metadata` + interceptor in new development instead of the `post_remove_rule` interceptor. + When both interceptors are used, this `post_remove_rule_with_metadata` interceptor runs after the + `post_remove_rule` interceptor. The (possibly modified) response returned by + `post_remove_rule` will be passed to + `post_remove_rule_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class OrganizationSecurityPoliciesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OrganizationSecurityPoliciesRestInterceptor + + +class OrganizationSecurityPoliciesRestTransport( + _BaseOrganizationSecurityPoliciesRestTransport +): + """REST backend synchronous transport for OrganizationSecurityPolicies. + + The OrganizationSecurityPolicies 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[OrganizationSecurityPoliciesRestInterceptor] = 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. + """ + # 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 OrganizationSecurityPoliciesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AddAssociation( + _BaseOrganizationSecurityPoliciesRestTransport._BaseAddAssociation, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.AddAssociation") + + @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.AddAssociationOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the add association method over HTTP. + + Args: + request (~.compute.AddAssociationOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.AddAssociation. + 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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseAddAssociation._get_http_options() + ) + + request, metadata = self._interceptor.pre_add_association(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseAddAssociation._get_transcoded_request( + http_options, request + ) + + body = _BaseOrganizationSecurityPoliciesRestTransport._BaseAddAssociation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseAddAssociation._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.OrganizationSecurityPoliciesClient.AddAssociation", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "AddAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + OrganizationSecurityPoliciesRestTransport._AddAssociation._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_add_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_add_association_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.OrganizationSecurityPoliciesClient.add_association", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "AddAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _AddRule( + _BaseOrganizationSecurityPoliciesRestTransport._BaseAddRule, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.AddRule") + + @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.AddRuleOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the add rule method over HTTP. + + Args: + request (~.compute.AddRuleOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.AddRule. + 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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseAddRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_add_rule(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseAddRule._get_transcoded_request( + http_options, request + ) + + body = _BaseOrganizationSecurityPoliciesRestTransport._BaseAddRule._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseAddRule._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.OrganizationSecurityPoliciesClient.AddRule", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "AddRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._AddRule._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_add_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_add_rule_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.OrganizationSecurityPoliciesClient.add_rule", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "AddRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CopyRules( + _BaseOrganizationSecurityPoliciesRestTransport._BaseCopyRules, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.CopyRules") + + @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.CopyRulesOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the copy rules method over HTTP. + + Args: + request (~.compute.CopyRulesOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.CopyRules. + 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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseCopyRules._get_http_options() + ) + + request, metadata = self._interceptor.pre_copy_rules(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseCopyRules._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseCopyRules._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.OrganizationSecurityPoliciesClient.CopyRules", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "CopyRules", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + OrganizationSecurityPoliciesRestTransport._CopyRules._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_copy_rules(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_copy_rules_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.OrganizationSecurityPoliciesClient.copy_rules", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "CopyRules", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Delete( + _BaseOrganizationSecurityPoliciesRestTransport._BaseDelete, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.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.DeleteOrganizationSecurityPolicyRequest, + *, + 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.DeleteOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseDelete._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseDelete._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._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.OrganizationSecurityPoliciesClient.Delete", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Delete", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._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.OrganizationSecurityPoliciesClient.delete", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Delete", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Get( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGet, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.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.GetOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.SecurityPolicy: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.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.SecurityPolicy: + Represents a Google Cloud Armor + security policy resource. Only external + backend services that use load balancers + can reference a security policy. For + more information, see Google Cloud Armor + security policy overview. + + """ + + http_options = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._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.OrganizationSecurityPoliciesClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._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.SecurityPolicy() + pb_resp = compute.SecurityPolicy.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.SecurityPolicy.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.OrganizationSecurityPoliciesClient.get", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAssociation( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGetAssociation, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.GetAssociation") + + @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.GetAssociationOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.SecurityPolicyAssociation: + r"""Call the get association method over HTTP. + + Args: + request (~.compute.GetAssociationOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.GetAssociation. + 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.SecurityPolicyAssociation: + + """ + + http_options = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGetAssociation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_association(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseGetAssociation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseGetAssociation._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.OrganizationSecurityPoliciesClient.GetAssociation", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "GetAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + OrganizationSecurityPoliciesRestTransport._GetAssociation._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.SecurityPolicyAssociation() + pb_resp = compute.SecurityPolicyAssociation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_association_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.SecurityPolicyAssociation.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.OrganizationSecurityPoliciesClient.get_association", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "GetAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRule( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGetRule, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.GetRule") + + @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.GetRuleOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.SecurityPolicyRule: + r"""Call the get rule method over HTTP. + + Args: + request (~.compute.GetRuleOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.GetRule. + 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.SecurityPolicyRule: + Represents a rule that describes one + or more match conditions along with the + action to be taken when traffic matches + this condition (allow or deny). + + """ + + http_options = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGetRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_rule(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseGetRule._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseGetRule._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.OrganizationSecurityPoliciesClient.GetRule", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "GetRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._GetRule._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.SecurityPolicyRule() + pb_resp = compute.SecurityPolicyRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_rule_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.SecurityPolicyRule.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.OrganizationSecurityPoliciesClient.get_rule", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "GetRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Insert( + _BaseOrganizationSecurityPoliciesRestTransport._BaseInsert, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.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.InsertOrganizationSecurityPolicyRequest, + *, + 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.InsertOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseInsert._get_http_options() + ) + + request, metadata = self._interceptor.pre_insert(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseInsert._get_transcoded_request( + http_options, request + ) + + body = _BaseOrganizationSecurityPoliciesRestTransport._BaseInsert._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._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.OrganizationSecurityPoliciesClient.Insert", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Insert", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._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.OrganizationSecurityPoliciesClient.insert", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Insert", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List( + _BaseOrganizationSecurityPoliciesRestTransport._BaseList, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.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.ListOrganizationSecurityPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.SecurityPolicyList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListOrganizationSecurityPoliciesRequest): + The request object. A request message for + OrganizationSecurityPolicies.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.SecurityPolicyList: + + """ + + http_options = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._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.OrganizationSecurityPoliciesClient.List", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._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.SecurityPolicyList() + pb_resp = compute.SecurityPolicyList.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.SecurityPolicyList.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.OrganizationSecurityPoliciesClient.list", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAssociations( + _BaseOrganizationSecurityPoliciesRestTransport._BaseListAssociations, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.ListAssociations") + + @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.ListAssociationsOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.OrganizationSecurityPoliciesListAssociationsResponse: + r"""Call the list associations method over HTTP. + + Args: + request (~.compute.ListAssociationsOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.ListAssociations. + 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.OrganizationSecurityPoliciesListAssociationsResponse: + + """ + + http_options = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseListAssociations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_associations( + request, metadata + ) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseListAssociations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseListAssociations._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.OrganizationSecurityPoliciesClient.ListAssociations", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "ListAssociations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._ListAssociations._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.OrganizationSecurityPoliciesListAssociationsResponse() + pb_resp = compute.OrganizationSecurityPoliciesListAssociationsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_associations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_associations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.OrganizationSecurityPoliciesListAssociationsResponse.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.OrganizationSecurityPoliciesClient.list_associations", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "ListAssociations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPreconfiguredExpressionSets( + _BaseOrganizationSecurityPoliciesRestTransport._BaseListPreconfiguredExpressionSets, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash( + "OrganizationSecurityPoliciesRestTransport.ListPreconfiguredExpressionSets" + ) + + @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.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse: + r"""Call the list preconfigured + expression sets method over HTTP. + + Args: + request (~.compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest): + The request object. A request message for + OrganizationSecurityPolicies.ListPreconfiguredExpressionSets. + 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.SecurityPoliciesListPreconfiguredExpressionSetsResponse: + + """ + + http_options = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseListPreconfiguredExpressionSets._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_list_preconfigured_expression_sets( + request, metadata + ) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseListPreconfiguredExpressionSets._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseListPreconfiguredExpressionSets._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.OrganizationSecurityPoliciesClient.ListPreconfiguredExpressionSets", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "ListPreconfiguredExpressionSets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._ListPreconfiguredExpressionSets._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.SecurityPoliciesListPreconfiguredExpressionSetsResponse() + pb_resp = ( + compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.pb(resp) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_preconfigured_expression_sets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_list_preconfigured_expression_sets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.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.OrganizationSecurityPoliciesClient.list_preconfigured_expression_sets", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "ListPreconfiguredExpressionSets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Move( + _BaseOrganizationSecurityPoliciesRestTransport._BaseMove, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.Move") + + @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.MoveOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the move method over HTTP. + + Args: + request (~.compute.MoveOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.Move. 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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseMove._get_http_options() + ) + + request, metadata = self._interceptor.pre_move(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseMove._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseMove._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.OrganizationSecurityPoliciesClient.Move", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Move", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._Move._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_move(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_move_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.OrganizationSecurityPoliciesClient.move", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Move", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Patch( + _BaseOrganizationSecurityPoliciesRestTransport._BasePatch, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.Patch") + + @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.PatchOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the patch method over HTTP. + + Args: + request (~.compute.PatchOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.Patch. 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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BasePatch._get_http_options() + ) + + request, metadata = self._interceptor.pre_patch(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BasePatch._get_transcoded_request( + http_options, request + ) + + body = _BaseOrganizationSecurityPoliciesRestTransport._BasePatch._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BasePatch._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.OrganizationSecurityPoliciesClient.Patch", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Patch", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._Patch._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_patch(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_patch_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.OrganizationSecurityPoliciesClient.patch", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "Patch", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PatchRule( + _BaseOrganizationSecurityPoliciesRestTransport._BasePatchRule, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.PatchRule") + + @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.PatchRuleOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the patch rule method over HTTP. + + Args: + request (~.compute.PatchRuleOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.PatchRule. + 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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BasePatchRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_patch_rule(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BasePatchRule._get_transcoded_request( + http_options, request + ) + + body = _BaseOrganizationSecurityPoliciesRestTransport._BasePatchRule._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BasePatchRule._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.OrganizationSecurityPoliciesClient.PatchRule", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "PatchRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + OrganizationSecurityPoliciesRestTransport._PatchRule._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_patch_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_patch_rule_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.OrganizationSecurityPoliciesClient.patch_rule", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "PatchRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RemoveAssociation( + _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveAssociation, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.RemoveAssociation") + + @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.RemoveAssociationOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the remove association method over HTTP. + + Args: + request (~.compute.RemoveAssociationOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.RemoveAssociation. + 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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveAssociation._get_http_options() + ) + + request, metadata = self._interceptor.pre_remove_association( + request, metadata + ) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveAssociation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveAssociation._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.OrganizationSecurityPoliciesClient.RemoveAssociation", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "RemoveAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationSecurityPoliciesRestTransport._RemoveAssociation._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_remove_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_remove_association_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.OrganizationSecurityPoliciesClient.remove_association", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "RemoveAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RemoveRule( + _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveRule, + OrganizationSecurityPoliciesRestStub, + ): + def __hash__(self): + return hash("OrganizationSecurityPoliciesRestTransport.RemoveRule") + + @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.RemoveRuleOrganizationSecurityPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the remove rule method over HTTP. + + Args: + request (~.compute.RemoveRuleOrganizationSecurityPolicyRequest): + The request object. A request message for + OrganizationSecurityPolicies.RemoveRule. + 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, read Handling 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 = ( + _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveRule._get_http_options() + ) + + request, metadata = self._interceptor.pre_remove_rule(request, metadata) + transcoded_request = _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveRule._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveRule._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.OrganizationSecurityPoliciesClient.RemoveRule", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "RemoveRule", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + OrganizationSecurityPoliciesRestTransport._RemoveRule._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_remove_rule(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_remove_rule_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.OrganizationSecurityPoliciesClient.remove_rule", + extra={ + "serviceName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "rpcName": "RemoveRule", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def add_association( + self, + ) -> Callable[ + [compute.AddAssociationOrganizationSecurityPolicyRequest], 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._AddAssociation(self._session, self._host, self._interceptor) # type: ignore + + @property + def add_rule( + self, + ) -> Callable[ + [compute.AddRuleOrganizationSecurityPolicyRequest], 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._AddRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def copy_rules( + self, + ) -> Callable[ + [compute.CopyRulesOrganizationSecurityPolicyRequest], 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._CopyRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete( + self, + ) -> Callable[[compute.DeleteOrganizationSecurityPolicyRequest], 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.GetOrganizationSecurityPolicyRequest], compute.SecurityPolicy + ]: + # 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 get_association( + self, + ) -> Callable[ + [compute.GetAssociationOrganizationSecurityPolicyRequest], + compute.SecurityPolicyAssociation, + ]: + # 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._GetAssociation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_rule( + self, + ) -> Callable[ + [compute.GetRuleOrganizationSecurityPolicyRequest], compute.SecurityPolicyRule + ]: + # 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._GetRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert( + self, + ) -> Callable[[compute.InsertOrganizationSecurityPolicyRequest], 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.ListOrganizationSecurityPoliciesRequest], compute.SecurityPolicyList + ]: + # 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 list_associations( + self, + ) -> Callable[ + [compute.ListAssociationsOrganizationSecurityPolicyRequest], + compute.OrganizationSecurityPoliciesListAssociationsResponse, + ]: + # 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._ListAssociations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_preconfigured_expression_sets( + self, + ) -> Callable[ + [compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest], + compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse, + ]: + # 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._ListPreconfiguredExpressionSets(self._session, self._host, self._interceptor) # type: ignore + + @property + def move( + self, + ) -> Callable[[compute.MoveOrganizationSecurityPolicyRequest], 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._Move(self._session, self._host, self._interceptor) # type: ignore + + @property + def patch( + self, + ) -> Callable[[compute.PatchOrganizationSecurityPolicyRequest], 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._Patch(self._session, self._host, self._interceptor) # type: ignore + + @property + def patch_rule( + self, + ) -> Callable[ + [compute.PatchRuleOrganizationSecurityPolicyRequest], 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._PatchRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_association( + self, + ) -> Callable[ + [compute.RemoveAssociationOrganizationSecurityPolicyRequest], 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._RemoveAssociation(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_rule( + self, + ) -> Callable[ + [compute.RemoveRuleOrganizationSecurityPolicyRequest], 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._RemoveRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("OrganizationSecurityPoliciesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/rest_base.py new file mode 100644 index 000000000000..097bcec2e4a6 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/organization_security_policies/transports/rest_base.py @@ -0,0 +1,844 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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, OrganizationSecurityPoliciesTransport + + +class _BaseOrganizationSecurityPoliciesRestTransport( + OrganizationSecurityPoliciesTransport +): + """Base REST backend transport for OrganizationSecurityPolicies. + + 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 _BaseAddAssociation: + 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/locations/global/securityPolicies/{security_policy}/addAssociation", + "body": "security_policy_association_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AddAssociationOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseAddAssociation._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseAddRule: + 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/locations/global/securityPolicies/{security_policy}/addRule", + "body": "security_policy_rule_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AddRuleOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseAddRule._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseCopyRules: + 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/locations/global/securityPolicies/{security_policy}/copyRules", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.CopyRulesOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseCopyRules._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/locations/global/securityPolicies/{security_policy}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._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/locations/global/securityPolicies/{security_policy}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseGetAssociation: + 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/locations/global/securityPolicies/{security_policy}/getAssociation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetAssociationOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGetAssociation._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseGetRule: + 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/locations/global/securityPolicies/{security_policy}/getRule", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetRuleOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseGetRule._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/locations/global/securityPolicies", + "body": "security_policy_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.InsertOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseInsert._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/locations/global/securityPolicies", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListOrganizationSecurityPoliciesRequest.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, + ) + ) + + return query_params + + class _BaseListAssociations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/locations/global/securityPolicies/listAssociations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListAssociationsOrganizationSecurityPolicyRequest.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, + ) + ) + + return query_params + + class _BaseListPreconfiguredExpressionSets: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/locations/global/securityPolicies/listPreconfiguredExpressionSets", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest.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, + ) + ) + + return query_params + + class _BaseMove: + 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/locations/global/securityPolicies/{security_policy}/move", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.MoveOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseMove._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BasePatch: + 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/locations/global/securityPolicies/{security_policy}", + "body": "security_policy_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.PatchOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BasePatch._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BasePatchRule: + 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/locations/global/securityPolicies/{security_policy}/patchRule", + "body": "security_policy_rule_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.PatchRuleOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BasePatchRule._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseRemoveAssociation: + 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/locations/global/securityPolicies/{security_policy}/removeAssociation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.RemoveAssociationOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveAssociation._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseRemoveRule: + 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/locations/global/securityPolicies/{security_policy}/removeRule", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.RemoveRuleOrganizationSecurityPolicyRequest.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( + _BaseOrganizationSecurityPoliciesRestTransport._BaseRemoveRule._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseOrganizationSecurityPoliciesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/__init__.py new file mode 100644 index 000000000000..32f31263a3df --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 PreviewFeaturesClient + +__all__ = ("PreviewFeaturesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/client.py new file mode 100644 index 000000000000..5752e3c21fdc --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/client.py @@ -0,0 +1,1247 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +import functools +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +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 +import google.protobuf + +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__) + +from google.api_core import extended_operation # type: ignore + +from google.cloud.compute_v1.services.preview_features import pagers +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, PreviewFeaturesTransport +from .transports.rest import PreviewFeaturesRestTransport + + +class PreviewFeaturesClientMeta(type): + """Metaclass for the PreviewFeatures 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[PreviewFeaturesTransport]] + _transport_registry["rest"] = PreviewFeaturesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PreviewFeaturesTransport]: + """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 PreviewFeaturesClient(metaclass=PreviewFeaturesClientMeta): + """The PreviewFeatures API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """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: + 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) + 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" + + @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: + PreviewFeaturesClient: 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: + PreviewFeaturesClient: 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) -> PreviewFeaturesTransport: + """Returns the transport used by the client instance. + + Returns: + PreviewFeaturesTransport: 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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true": + 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 = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true", 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 + ): + """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 = PreviewFeaturesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PreviewFeaturesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PreviewFeaturesClient._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 = PreviewFeaturesClient._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): + """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, PreviewFeaturesTransport, Callable[..., PreviewFeaturesTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the preview features 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,PreviewFeaturesTransport,Callable[..., PreviewFeaturesTransport]]]): + 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 PreviewFeaturesTransport 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, + ) = PreviewFeaturesClient._read_environment_variables() + self._client_cert_source = PreviewFeaturesClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = PreviewFeaturesClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # 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, PreviewFeaturesTransport) + if transport_provided: + # transport is a PreviewFeaturesTransport 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(PreviewFeaturesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or PreviewFeaturesClient._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[PreviewFeaturesTransport], Callable[..., PreviewFeaturesTransport] + ] = ( + PreviewFeaturesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PreviewFeaturesTransport], 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.PreviewFeaturesClient`.", + extra={ + "serviceName": "google.cloud.compute.v1.PreviewFeatures", + "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.PreviewFeatures", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetPreviewFeatureRequest, dict]] = None, + *, + project: Optional[str] = None, + preview_feature: 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.PreviewFeature: + r"""Returns the details of the given PreviewFeature. + + .. 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.PreviewFeaturesClient() + + # Initialize request argument(s) + request = compute_v1.GetPreviewFeatureRequest( + preview_feature="preview_feature_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.GetPreviewFeatureRequest, dict]): + The request object. A request message for + PreviewFeatures.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. + preview_feature (str): + Name of the PreviewFeature for this + request. + + This corresponds to the ``preview_feature`` 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.PreviewFeature: + Represents a single Google Compute + Engine preview feature. + + """ + # 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, preview_feature] + 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.GetPreviewFeatureRequest): + request = compute.GetPreviewFeatureRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if preview_feature is not None: + request.preview_feature = preview_feature + + # 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), + ("preview_feature", request.preview_feature), + ) + ), + ) + + # 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.ListPreviewFeaturesRequest, 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"""Returns the details of the given PreviewFeature. + + .. 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.PreviewFeaturesClient() + + # Initialize request argument(s) + request = compute_v1.ListPreviewFeaturesRequest( + 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.ListPreviewFeaturesRequest, dict]): + The request object. A request message for + PreviewFeatures.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.preview_features.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.ListPreviewFeaturesRequest): + request = compute.ListPreviewFeaturesRequest(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.UpdatePreviewFeatureRequest, dict]] = None, + *, + project: Optional[str] = None, + preview_feature: Optional[str] = None, + preview_feature_resource: Optional[compute.PreviewFeature] = 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"""Patches the given PreviewFeature. This method is used + to enable or disable a PreviewFeature. + + .. 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.PreviewFeaturesClient() + + # Initialize request argument(s) + request = compute_v1.UpdatePreviewFeatureRequest( + preview_feature="preview_feature_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.UpdatePreviewFeatureRequest, dict]): + The request object. A request message for + PreviewFeatures.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. + preview_feature (str): + Name of the PreviewFeature for this + request. + + This corresponds to the ``preview_feature`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + preview_feature_resource (google.cloud.compute_v1.types.PreviewFeature): + The body resource for this request + This corresponds to the ``preview_feature_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, preview_feature, preview_feature_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.UpdatePreviewFeatureRequest): + request = compute.UpdatePreviewFeatureRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if preview_feature is not None: + request.preview_feature = preview_feature + if preview_feature_resource is not None: + request.preview_feature_resource = preview_feature_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), + ("preview_feature", request.preview_feature), + ) + ), + ) + + # 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.UpdatePreviewFeatureRequest, dict]] = None, + *, + project: Optional[str] = None, + preview_feature: Optional[str] = None, + preview_feature_resource: Optional[compute.PreviewFeature] = 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"""Patches the given PreviewFeature. This method is used + to enable or disable a PreviewFeature. + + .. 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.PreviewFeaturesClient() + + # Initialize request argument(s) + request = compute_v1.UpdatePreviewFeatureRequest( + preview_feature="preview_feature_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.UpdatePreviewFeatureRequest, dict]): + The request object. A request message for + PreviewFeatures.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. + preview_feature (str): + Name of the PreviewFeature for this + request. + + This corresponds to the ``preview_feature`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + preview_feature_resource (google.cloud.compute_v1.types.PreviewFeature): + The body resource for this request + This corresponds to the ``preview_feature_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, preview_feature, preview_feature_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.UpdatePreviewFeatureRequest): + request = compute.UpdatePreviewFeatureRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if preview_feature is not None: + request.preview_feature = preview_feature + if preview_feature_resource is not None: + request.preview_feature_resource = preview_feature_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), + ("preview_feature", request.preview_feature), + ) + ), + ) + + # 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) -> "PreviewFeaturesClient": + 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__ = ("PreviewFeaturesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/pagers.py new file mode 100644 index 000000000000..223a9062a12d --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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.PreviewFeatureList` 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.PreviewFeatureList` + 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.PreviewFeatureList], + request: compute.ListPreviewFeaturesRequest, + response: compute.PreviewFeatureList, + *, + 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.ListPreviewFeaturesRequest): + The initial request object. + response (google.cloud.compute_v1.types.PreviewFeatureList): + 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.ListPreviewFeaturesRequest(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.PreviewFeatureList]: + 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.PreviewFeature]: + 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/preview_features/transports/README.rst b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/README.rst new file mode 100644 index 000000000000..808797795f8f --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PreviewFeaturesTransport` is the ABC for all transports. +- public child `PreviewFeaturesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PreviewFeaturesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePreviewFeaturesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PreviewFeaturesRestTransport` 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/preview_features/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/__init__.py new file mode 100644 index 000000000000..58f8861b3279 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 PreviewFeaturesTransport +from .rest import PreviewFeaturesRestInterceptor, PreviewFeaturesRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PreviewFeaturesTransport]] +_transport_registry["rest"] = PreviewFeaturesRestTransport + +__all__ = ( + "PreviewFeaturesTransport", + "PreviewFeaturesRestTransport", + "PreviewFeaturesRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/base.py new file mode 100644 index 000000000000..153384d24954 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/base.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +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 PreviewFeaturesTransport(abc.ABC): + """Abstract transport class for PreviewFeatures.""" + + 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. + """ + self._extended_operations_services: Dict[str, Any] = {} + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # 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_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # 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 + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get: gapic_v1.method.wrap_method( + self.get, + default_timeout=None, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_timeout=None, + client_info=client_info, + ), + self.update: gapic_v1.method.wrap_method( + self.update, + default_timeout=None, + 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 get( + self, + ) -> Callable[ + [compute.GetPreviewFeatureRequest], + Union[compute.PreviewFeature, Awaitable[compute.PreviewFeature]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListPreviewFeaturesRequest], + Union[compute.PreviewFeatureList, Awaitable[compute.PreviewFeatureList]], + ]: + raise NotImplementedError() + + @property + def update( + self, + ) -> Callable[ + [compute.UpdatePreviewFeatureRequest], + 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__ = ("PreviewFeaturesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/rest.py new file mode 100644 index 000000000000..fdc036cb38e1 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/rest.py @@ -0,0 +1,836 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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 +import google.protobuf +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 _BasePreviewFeaturesRestTransport + +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 PreviewFeaturesRestInterceptor: + """Interceptor for PreviewFeatures. + + 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 PreviewFeaturesRestTransport. + + .. code-block:: python + class MyCustomPreviewFeaturesInterceptor(PreviewFeaturesRestInterceptor): + 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 + + 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 = PreviewFeaturesRestTransport(interceptor=MyCustomPreviewFeaturesInterceptor()) + client = PreviewFeaturesClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetPreviewFeatureRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetPreviewFeatureRequest, 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 PreviewFeatures server. + """ + return request, metadata + + def post_get(self, response: compute.PreviewFeature) -> compute.PreviewFeature: + """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 PreviewFeatures 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.PreviewFeature, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.PreviewFeature, 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 PreviewFeatures 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.ListPreviewFeaturesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListPreviewFeaturesRequest, 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 PreviewFeatures server. + """ + return request, metadata + + def post_list( + self, response: compute.PreviewFeatureList + ) -> compute.PreviewFeatureList: + """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 PreviewFeatures 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.PreviewFeatureList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.PreviewFeatureList, 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 PreviewFeatures 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.UpdatePreviewFeatureRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.UpdatePreviewFeatureRequest, 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 PreviewFeatures 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 PreviewFeatures 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 PreviewFeatures 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 PreviewFeaturesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PreviewFeaturesRestInterceptor + + +class PreviewFeaturesRestTransport(_BasePreviewFeaturesRestTransport): + """REST backend synchronous transport for PreviewFeatures. + + The PreviewFeatures 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[PreviewFeaturesRestInterceptor] = 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. + """ + # 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 PreviewFeaturesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get(_BasePreviewFeaturesRestTransport._BaseGet, PreviewFeaturesRestStub): + def __hash__(self): + return hash("PreviewFeaturesRestTransport.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.GetPreviewFeatureRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.PreviewFeature: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetPreviewFeatureRequest): + The request object. A request message for + PreviewFeatures.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.PreviewFeature: + Represents a single Google Compute + Engine preview feature. + + """ + + http_options = ( + _BasePreviewFeaturesRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BasePreviewFeaturesRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePreviewFeaturesRestTransport._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.PreviewFeaturesClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1.PreviewFeatures", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PreviewFeaturesRestTransport._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.PreviewFeature() + pb_resp = compute.PreviewFeature.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.PreviewFeature.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.PreviewFeaturesClient.get", + extra={ + "serviceName": "google.cloud.compute.v1.PreviewFeatures", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List(_BasePreviewFeaturesRestTransport._BaseList, PreviewFeaturesRestStub): + def __hash__(self): + return hash("PreviewFeaturesRestTransport.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.ListPreviewFeaturesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.PreviewFeatureList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListPreviewFeaturesRequest): + The request object. A request message for + PreviewFeatures.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.PreviewFeatureList: + + """ + + http_options = ( + _BasePreviewFeaturesRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = ( + _BasePreviewFeaturesRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePreviewFeaturesRestTransport._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.PreviewFeaturesClient.List", + extra={ + "serviceName": "google.cloud.compute.v1.PreviewFeatures", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PreviewFeaturesRestTransport._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.PreviewFeatureList() + pb_resp = compute.PreviewFeatureList.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.PreviewFeatureList.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.PreviewFeaturesClient.list", + extra={ + "serviceName": "google.cloud.compute.v1.PreviewFeatures", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Update( + _BasePreviewFeaturesRestTransport._BaseUpdate, PreviewFeaturesRestStub + ): + def __hash__(self): + return hash("PreviewFeaturesRestTransport.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.UpdatePreviewFeatureRequest, + *, + 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.UpdatePreviewFeatureRequest): + The request object. A request message for + PreviewFeatures.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, read Handling 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 = ( + _BasePreviewFeaturesRestTransport._BaseUpdate._get_http_options() + ) + + request, metadata = self._interceptor.pre_update(request, metadata) + transcoded_request = ( + _BasePreviewFeaturesRestTransport._BaseUpdate._get_transcoded_request( + http_options, request + ) + ) + + body = _BasePreviewFeaturesRestTransport._BaseUpdate._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BasePreviewFeaturesRestTransport._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.PreviewFeaturesClient.Update", + extra={ + "serviceName": "google.cloud.compute.v1.PreviewFeatures", + "rpcName": "Update", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PreviewFeaturesRestTransport._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.PreviewFeaturesClient.update", + extra={ + "serviceName": "google.cloud.compute.v1.PreviewFeatures", + "rpcName": "Update", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get( + self, + ) -> Callable[[compute.GetPreviewFeatureRequest], compute.PreviewFeature]: + # 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.ListPreviewFeaturesRequest], compute.PreviewFeatureList]: + # 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.UpdatePreviewFeatureRequest], 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__ = ("PreviewFeaturesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/rest_base.py new file mode 100644 index 000000000000..0439277f6086 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/preview_features/transports/rest_base.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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, PreviewFeaturesTransport + + +class _BasePreviewFeaturesRestTransport(PreviewFeaturesTransport): + """Base REST backend transport for PreviewFeatures. + + 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 _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/previewFeatures/{preview_feature}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetPreviewFeatureRequest.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( + _BasePreviewFeaturesRestTransport._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/previewFeatures", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListPreviewFeaturesRequest.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( + _BasePreviewFeaturesRestTransport._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/previewFeatures/{preview_feature}", + "body": "preview_feature_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.UpdatePreviewFeatureRequest.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( + _BasePreviewFeaturesRestTransport._BaseUpdate._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BasePreviewFeaturesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/client.py index 52af00f746fc..4f57d458b9d1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/client.py @@ -1328,6 +1328,369 @@ def error_code(self): # Done; return the response. return response + def report_faulty_unary( + self, + request: Optional[ + Union[compute.ReportFaultyReservationSubBlockRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + parent_name: Optional[str] = None, + reservation_sub_block: Optional[str] = None, + reservation_sub_blocks_report_faulty_request_resource: Optional[ + compute.ReservationSubBlocksReportFaultyRequest + ] = 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"""Allows customers to report a faulty subBlock. + + .. 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_report_faulty(): + # Create a client + client = compute_v1.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1.ReportFaultyReservationSubBlockRequest( + parent_name="parent_name_value", + project="project_value", + reservation_sub_block="reservation_sub_block_value", + zone="zone_value", + ) + + # Make the request + response = client.report_faulty(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ReportFaultyReservationSubBlockRequest, dict]): + The request object. A request message for + ReservationSubBlocks.ReportFaulty. 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. + zone (str): + Name of the zone for this request. + Zone name should conform to RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + parent_name (str): + The name of the parent reservation and parent block. In + the format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + + This corresponds to the ``parent_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_block (str): + The name of the reservation subBlock. + Name should conform to RFC1035 or be a + resource ID. + + This corresponds to the ``reservation_sub_block`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_blocks_report_faulty_request_resource (google.cloud.compute_v1.types.ReservationSubBlocksReportFaultyRequest): + The body resource for this request + This corresponds to the ``reservation_sub_blocks_report_faulty_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, + zone, + parent_name, + reservation_sub_block, + reservation_sub_blocks_report_faulty_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.ReportFaultyReservationSubBlockRequest): + request = compute.ReportFaultyReservationSubBlockRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if parent_name is not None: + request.parent_name = parent_name + if reservation_sub_block is not None: + request.reservation_sub_block = reservation_sub_block + if reservation_sub_blocks_report_faulty_request_resource is not None: + request.reservation_sub_blocks_report_faulty_request_resource = ( + reservation_sub_blocks_report_faulty_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report_faulty] + + # 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), + ("zone", request.zone), + ("parent_name", request.parent_name), + ("reservation_sub_block", request.reservation_sub_block), + ) + ), + ) + + # 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 report_faulty( + self, + request: Optional[ + Union[compute.ReportFaultyReservationSubBlockRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + parent_name: Optional[str] = None, + reservation_sub_block: Optional[str] = None, + reservation_sub_blocks_report_faulty_request_resource: Optional[ + compute.ReservationSubBlocksReportFaultyRequest + ] = 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"""Allows customers to report a faulty subBlock. + + .. 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_report_faulty(): + # Create a client + client = compute_v1.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1.ReportFaultyReservationSubBlockRequest( + parent_name="parent_name_value", + project="project_value", + reservation_sub_block="reservation_sub_block_value", + zone="zone_value", + ) + + # Make the request + response = client.report_faulty(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ReportFaultyReservationSubBlockRequest, dict]): + The request object. A request message for + ReservationSubBlocks.ReportFaulty. 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. + zone (str): + Name of the zone for this request. + Zone name should conform to RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + parent_name (str): + The name of the parent reservation and parent block. In + the format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + + This corresponds to the ``parent_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_block (str): + The name of the reservation subBlock. + Name should conform to RFC1035 or be a + resource ID. + + This corresponds to the ``reservation_sub_block`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_blocks_report_faulty_request_resource (google.cloud.compute_v1.types.ReservationSubBlocksReportFaultyRequest): + The body resource for this request + This corresponds to the ``reservation_sub_blocks_report_faulty_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, + zone, + parent_name, + reservation_sub_block, + reservation_sub_blocks_report_faulty_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.ReportFaultyReservationSubBlockRequest): + request = compute.ReportFaultyReservationSubBlockRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if parent_name is not None: + request.parent_name = parent_name + if reservation_sub_block is not None: + request.reservation_sub_block = reservation_sub_block + if reservation_sub_blocks_report_faulty_request_resource is not None: + request.reservation_sub_blocks_report_faulty_request_resource = ( + reservation_sub_blocks_report_faulty_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report_faulty] + + # 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), + ("zone", request.zone), + ("parent_name", request.parent_name), + ("reservation_sub_block", request.reservation_sub_block), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + 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) -> "ReservationSubBlocksClient": return self diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/base.py index ac6d27f40f96..485ab0fe8d3e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/base.py @@ -153,6 +153,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.report_faulty: gapic_v1.method.wrap_method( + self.report_faulty, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -197,6 +202,15 @@ def perform_maintenance( ]: raise NotImplementedError() + @property + def report_faulty( + self, + ) -> Callable[ + [compute.ReportFaultyReservationSubBlockRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/rest.py index 8d806453f949..4d5c7f483178 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/rest.py @@ -96,6 +96,14 @@ def post_perform_maintenance(self, response): logging.log(f"Received response: {response}") return response + def pre_report_faulty(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_report_faulty(self, response): + logging.log(f"Received response: {response}") + return response + transport = ReservationSubBlocksRestTransport(interceptor=MyCustomReservationSubBlocksInterceptor()) client = ReservationSubBlocksClient(transport=transport) @@ -252,6 +260,53 @@ def post_perform_maintenance_with_metadata( """ return response, metadata + def pre_report_faulty( + self, + request: compute.ReportFaultyReservationSubBlockRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ReportFaultyReservationSubBlockRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for report_faulty + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationSubBlocks server. + """ + return request, metadata + + def post_report_faulty(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for report_faulty + + DEPRECATED. Please use the `post_report_faulty_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ReservationSubBlocks server but before + it is returned to user code. This `post_report_faulty` interceptor runs + before the `post_report_faulty_with_metadata` interceptor. + """ + return response + + def post_report_faulty_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 report_faulty + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ReservationSubBlocks server but before it is returned to user code. + + We recommend only using this `post_report_faulty_with_metadata` + interceptor in new development instead of the `post_report_faulty` interceptor. + When both interceptors are used, this `post_report_faulty_with_metadata` interceptor runs after the + `post_report_faulty` interceptor. The (possibly modified) response returned by + `post_report_faulty` will be passed to + `post_report_faulty_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class ReservationSubBlocksRestStub: @@ -812,6 +867,176 @@ def __call__( ) return resp + class _ReportFaulty( + _BaseReservationSubBlocksRestTransport._BaseReportFaulty, + ReservationSubBlocksRestStub, + ): + def __hash__(self): + return hash("ReservationSubBlocksRestTransport.ReportFaulty") + + @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.ReportFaultyReservationSubBlockRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the report faulty method over HTTP. + + Args: + request (~.compute.ReportFaultyReservationSubBlockRequest): + The request object. A request message for + ReservationSubBlocks.ReportFaulty. 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, read Handling 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 = ( + _BaseReservationSubBlocksRestTransport._BaseReportFaulty._get_http_options() + ) + + request, metadata = self._interceptor.pre_report_faulty(request, metadata) + transcoded_request = _BaseReservationSubBlocksRestTransport._BaseReportFaulty._get_transcoded_request( + http_options, request + ) + + body = _BaseReservationSubBlocksRestTransport._BaseReportFaulty._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseReservationSubBlocksRestTransport._BaseReportFaulty._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.ReservationSubBlocksClient.ReportFaulty", + extra={ + "serviceName": "google.cloud.compute.v1.ReservationSubBlocks", + "rpcName": "ReportFaulty", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ReservationSubBlocksRestTransport._ReportFaulty._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_report_faulty(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_report_faulty_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.ReservationSubBlocksClient.report_faulty", + extra={ + "serviceName": "google.cloud.compute.v1.ReservationSubBlocks", + "rpcName": "ReportFaulty", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def get( self, @@ -843,6 +1068,14 @@ def perform_maintenance( # In C++ this would require a dynamic_cast return self._PerformMaintenance(self._session, self._host, self._interceptor) # type: ignore + @property + def report_faulty( + self, + ) -> Callable[[compute.ReportFaultyReservationSubBlockRequest], 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._ReportFaulty(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/rest_base.py index 0ef3342b1397..a33d3e593a79 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/rest_base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservation_sub_blocks/transports/rest_base.py @@ -227,5 +227,61 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseReportFaulty: + 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}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty", + "body": "reservation_sub_blocks_report_faulty_request_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ReportFaultyReservationSubBlockRequest.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( + _BaseReservationSubBlocksRestTransport._BaseReportFaulty._get_unset_required_fields( + query_params + ) + ) + + return query_params + __all__ = ("_BaseReservationSubBlocksRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py index 16d7a1166026..dc599ffc6d3f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py @@ -1036,7 +1036,7 @@ def sample_get(): resource. You can use snapshots to back up data on a regular interval. For more information, read Creating persistent - disk snapshots. LINT.IfChange + disk snapshots. """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/rest.py index 7b8e82997a27..1274c3191b2b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/transports/rest.py @@ -816,7 +816,7 @@ def __call__( resource. You can use snapshots to back up data on a regular interval. For more information, read Creating persistent - disk snapshots. LINT.IfChange + disk snapshots. """ 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 1fdff31b4056..4797d7d23523 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 @@ -26,6 +26,7 @@ AddAccessConfigInstanceRequest, AddAssociationFirewallPolicyRequest, AddAssociationNetworkFirewallPolicyRequest, + AddAssociationOrganizationSecurityPolicyRequest, AddAssociationRegionNetworkFirewallPolicyRequest, AddHealthCheckTargetPoolRequest, AddInstancesInstanceGroupRequest, @@ -43,6 +44,7 @@ AddressList, AddRuleFirewallPolicyRequest, AddRuleNetworkFirewallPolicyRequest, + AddRuleOrganizationSecurityPolicyRequest, AddRuleRegionNetworkFirewallPolicyRequest, AddRuleRegionSecurityPolicyRequest, AddRuleSecurityPolicyRequest, @@ -200,6 +202,7 @@ ConnectionDraining, ConsistentHashLoadBalancerSettings, ConsistentHashLoadBalancerSettingsHttpCookie, + CopyRulesOrganizationSecurityPolicyRequest, CorsPolicy, CreateInstancesInstanceGroupManagerRequest, CreateInstancesRegionInstanceGroupManagerRequest, @@ -211,6 +214,7 @@ CustomErrorResponsePolicy, CustomErrorResponsePolicyCustomErrorResponseRule, Data, + Date, DeleteAccessConfigInstanceRequest, DeleteAddressRequest, DeleteAutoscalerRequest, @@ -254,6 +258,7 @@ DeleteNodeGroupRequest, DeleteNodesNodeGroupRequest, DeleteNodeTemplateRequest, + DeleteOrganizationSecurityPolicyRequest, DeletePacketMirroringRequest, DeletePerInstanceConfigsInstanceGroupManagerRequest, DeletePerInstanceConfigsRegionInstanceGroupManagerRequest, @@ -377,6 +382,7 @@ GetAddressRequest, GetAssociationFirewallPolicyRequest, GetAssociationNetworkFirewallPolicyRequest, + GetAssociationOrganizationSecurityPolicyRequest, GetAssociationRegionNetworkFirewallPolicyRequest, GetAutoscalerRequest, GetBackendBucketRequest, @@ -387,6 +393,8 @@ GetEffectiveFirewallsInstanceRequest, GetEffectiveFirewallsNetworkRequest, GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest, + GetEffectiveSecurityPoliciesBackendServiceRequest, + GetEffectiveSecurityPoliciesBackendServiceResponse, GetExternalVpnGatewayRequest, GetFirewallPolicyRequest, GetFirewallRequest, @@ -462,8 +470,10 @@ GetNodeTypeRequest, GetOperationalStatusInterconnectAttachmentGroupRequest, GetOperationalStatusInterconnectGroupRequest, + GetOrganizationSecurityPolicyRequest, GetPacketMirroringRequest, GetPacketMirroringRuleNetworkFirewallPolicyRequest, + GetPreviewFeatureRequest, GetProjectRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, @@ -500,6 +510,7 @@ GetRouterStatusRouterRequest, GetRuleFirewallPolicyRequest, GetRuleNetworkFirewallPolicyRequest, + GetRuleOrganizationSecurityPolicyRequest, GetRuleRegionNetworkFirewallPolicyRequest, GetRuleRegionSecurityPolicyRequest, GetRuleSecurityPolicyRequest, @@ -575,6 +586,7 @@ Image, ImageFamilyView, ImageList, + ImageParams, InitialStateConfig, InsertAddressRequest, InsertAutoscalerRequest, @@ -610,6 +622,7 @@ InsertNetworkRequest, InsertNodeGroupRequest, InsertNodeTemplateRequest, + InsertOrganizationSecurityPolicyRequest, InsertPacketMirroringRequest, InsertPublicAdvertisedPrefixeRequest, InsertPublicDelegatedPrefixeRequest, @@ -825,6 +838,7 @@ ListAcceleratorTypesRequest, ListAddressesRequest, ListAssociationsFirewallPolicyRequest, + ListAssociationsOrganizationSecurityPolicyRequest, ListAutoscalersRequest, ListAvailableFeaturesRegionSslPoliciesRequest, ListAvailableFeaturesSslPoliciesRequest, @@ -879,11 +893,14 @@ ListNodesNodeGroupsRequest, ListNodeTemplatesRequest, ListNodeTypesRequest, + ListOrganizationSecurityPoliciesRequest, ListPacketMirroringsRequest, ListPeeringRoutesNetworksRequest, ListPerInstanceConfigsInstanceGroupManagersRequest, ListPerInstanceConfigsRegionInstanceGroupManagersRequest, + ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, ListPreconfiguredExpressionSetsSecurityPoliciesRequest, + ListPreviewFeaturesRequest, ListPublicAdvertisedPrefixesRequest, ListPublicDelegatedPrefixesRequest, ListReferrersInstancesRequest, @@ -968,6 +985,7 @@ MoveFirewallPolicyRequest, MoveGlobalAddressRequest, MoveInstanceProjectRequest, + MoveOrganizationSecurityPolicyRequest, NamedPort, NatIpInfo, NatIpInfoNatIpInfoMapping, @@ -1045,6 +1063,7 @@ OperationAggregatedList, OperationList, OperationsScopedList, + OrganizationSecurityPoliciesListAssociationsResponse, OutlierDetection, PacketIntervals, PacketMirroring, @@ -1078,6 +1097,7 @@ PatchNetworkFirewallPolicyRequest, PatchNetworkRequest, PatchNodeGroupRequest, + PatchOrganizationSecurityPolicyRequest, PatchPacketMirroringRequest, PatchPacketMirroringRuleNetworkFirewallPolicyRequest, PatchPerInstanceConfigsInstanceGroupManagerRequest, @@ -1099,6 +1119,7 @@ PatchRouterRequest, PatchRuleFirewallPolicyRequest, PatchRuleNetworkFirewallPolicyRequest, + PatchRuleOrganizationSecurityPolicyRequest, PatchRuleRegionNetworkFirewallPolicyRequest, PatchRuleRegionSecurityPolicyRequest, PatchRuleSecurityPolicyRequest, @@ -1125,6 +1146,12 @@ PreservedStatePreservedDisk, PreservedStatePreservedNetworkIp, PreservedStatePreservedNetworkIpIpAddress, + PreviewFeature, + PreviewFeatureList, + PreviewFeatureRolloutOperation, + PreviewFeatureRolloutOperationRolloutInput, + PreviewFeatureStatus, + PreviewFeatureStatusReleaseStatus, PreviewRouterRequest, Project, ProjectsDisableXpnResourceRequest, @@ -1189,6 +1216,7 @@ RegionUrlMapsValidateRequest, RemoveAssociationFirewallPolicyRequest, RemoveAssociationNetworkFirewallPolicyRequest, + RemoveAssociationOrganizationSecurityPolicyRequest, RemoveAssociationRegionNetworkFirewallPolicyRequest, RemoveHealthCheckTargetPoolRequest, RemoveInstancesInstanceGroupRequest, @@ -1200,9 +1228,11 @@ RemoveResourcePoliciesRegionDiskRequest, RemoveRuleFirewallPolicyRequest, RemoveRuleNetworkFirewallPolicyRequest, + RemoveRuleOrganizationSecurityPolicyRequest, RemoveRuleRegionNetworkFirewallPolicyRequest, RemoveRuleRegionSecurityPolicyRequest, RemoveRuleSecurityPolicyRequest, + ReportFaultyReservationSubBlockRequest, ReportHostAsFaultyInstanceRequest, RequestMirrorPolicy, RequestRemovePeeringNetworkRequest, @@ -1227,6 +1257,8 @@ ReservationSubBlockPhysicalTopology, ReservationSubBlocksGetResponse, ReservationSubBlocksListResponse, + ReservationSubBlocksReportFaultyRequest, + ReservationSubBlocksReportFaultyRequestFaultReason, ResetInstanceRequest, ResizeDiskRequest, ResizeInstanceGroupManagerRequest, @@ -1312,6 +1344,7 @@ SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfigThresholdConfigTrafficGranularityConfig, SecurityPolicyAdvancedOptionsConfig, SecurityPolicyAdvancedOptionsConfigJsonCustomConfig, + SecurityPolicyAssociation, SecurityPolicyDdosProtectionConfig, SecurityPolicyList, SecurityPolicyRecaptchaOptionsConfig, @@ -1453,6 +1486,7 @@ SimulateMaintenanceEventNodeGroupRequest, Snapshot, SnapshotList, + SnapshotParams, SnapshotSettings, SnapshotSettingsStorageLocationSettings, SnapshotSettingsStorageLocationSettingsStorageLocationPreference, @@ -1620,6 +1654,7 @@ UpdatePeeringNetworkRequest, UpdatePerInstanceConfigsInstanceGroupManagerRequest, UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest, + UpdatePreviewFeatureRequest, UpdateRegionAutoscalerRequest, UpdateRegionBackendServiceRequest, UpdateRegionCommitmentRequest, @@ -1701,6 +1736,7 @@ "AddAccessConfigInstanceRequest", "AddAssociationFirewallPolicyRequest", "AddAssociationNetworkFirewallPolicyRequest", + "AddAssociationOrganizationSecurityPolicyRequest", "AddAssociationRegionNetworkFirewallPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstancesInstanceGroupRequest", @@ -1718,6 +1754,7 @@ "AddressList", "AddRuleFirewallPolicyRequest", "AddRuleNetworkFirewallPolicyRequest", + "AddRuleOrganizationSecurityPolicyRequest", "AddRuleRegionNetworkFirewallPolicyRequest", "AddRuleRegionSecurityPolicyRequest", "AddRuleSecurityPolicyRequest", @@ -1875,6 +1912,7 @@ "ConnectionDraining", "ConsistentHashLoadBalancerSettings", "ConsistentHashLoadBalancerSettingsHttpCookie", + "CopyRulesOrganizationSecurityPolicyRequest", "CorsPolicy", "CreateInstancesInstanceGroupManagerRequest", "CreateInstancesRegionInstanceGroupManagerRequest", @@ -1886,6 +1924,7 @@ "CustomErrorResponsePolicy", "CustomErrorResponsePolicyCustomErrorResponseRule", "Data", + "Date", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -1929,6 +1968,7 @@ "DeleteNodeGroupRequest", "DeleteNodesNodeGroupRequest", "DeleteNodeTemplateRequest", + "DeleteOrganizationSecurityPolicyRequest", "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", @@ -2052,6 +2092,7 @@ "GetAddressRequest", "GetAssociationFirewallPolicyRequest", "GetAssociationNetworkFirewallPolicyRequest", + "GetAssociationOrganizationSecurityPolicyRequest", "GetAssociationRegionNetworkFirewallPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", @@ -2062,6 +2103,8 @@ "GetEffectiveFirewallsInstanceRequest", "GetEffectiveFirewallsNetworkRequest", "GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest", + "GetEffectiveSecurityPoliciesBackendServiceRequest", + "GetEffectiveSecurityPoliciesBackendServiceResponse", "GetExternalVpnGatewayRequest", "GetFirewallPolicyRequest", "GetFirewallRequest", @@ -2137,8 +2180,10 @@ "GetNodeTypeRequest", "GetOperationalStatusInterconnectAttachmentGroupRequest", "GetOperationalStatusInterconnectGroupRequest", + "GetOrganizationSecurityPolicyRequest", "GetPacketMirroringRequest", "GetPacketMirroringRuleNetworkFirewallPolicyRequest", + "GetPreviewFeatureRequest", "GetProjectRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", @@ -2175,6 +2220,7 @@ "GetRouterStatusRouterRequest", "GetRuleFirewallPolicyRequest", "GetRuleNetworkFirewallPolicyRequest", + "GetRuleOrganizationSecurityPolicyRequest", "GetRuleRegionNetworkFirewallPolicyRequest", "GetRuleRegionSecurityPolicyRequest", "GetRuleSecurityPolicyRequest", @@ -2250,6 +2296,7 @@ "Image", "ImageFamilyView", "ImageList", + "ImageParams", "InitialStateConfig", "InsertAddressRequest", "InsertAutoscalerRequest", @@ -2285,6 +2332,7 @@ "InsertNetworkRequest", "InsertNodeGroupRequest", "InsertNodeTemplateRequest", + "InsertOrganizationSecurityPolicyRequest", "InsertPacketMirroringRequest", "InsertPublicAdvertisedPrefixeRequest", "InsertPublicDelegatedPrefixeRequest", @@ -2500,6 +2548,7 @@ "ListAcceleratorTypesRequest", "ListAddressesRequest", "ListAssociationsFirewallPolicyRequest", + "ListAssociationsOrganizationSecurityPolicyRequest", "ListAutoscalersRequest", "ListAvailableFeaturesRegionSslPoliciesRequest", "ListAvailableFeaturesSslPoliciesRequest", @@ -2554,11 +2603,14 @@ "ListNodesNodeGroupsRequest", "ListNodeTemplatesRequest", "ListNodeTypesRequest", + "ListOrganizationSecurityPoliciesRequest", "ListPacketMirroringsRequest", "ListPeeringRoutesNetworksRequest", "ListPerInstanceConfigsInstanceGroupManagersRequest", "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", + "ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest", "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", + "ListPreviewFeaturesRequest", "ListPublicAdvertisedPrefixesRequest", "ListPublicDelegatedPrefixesRequest", "ListReferrersInstancesRequest", @@ -2643,6 +2695,7 @@ "MoveFirewallPolicyRequest", "MoveGlobalAddressRequest", "MoveInstanceProjectRequest", + "MoveOrganizationSecurityPolicyRequest", "NamedPort", "NatIpInfo", "NatIpInfoNatIpInfoMapping", @@ -2720,6 +2773,7 @@ "OperationAggregatedList", "OperationList", "OperationsScopedList", + "OrganizationSecurityPoliciesListAssociationsResponse", "OutlierDetection", "PacketIntervals", "PacketMirroring", @@ -2753,6 +2807,7 @@ "PatchNetworkFirewallPolicyRequest", "PatchNetworkRequest", "PatchNodeGroupRequest", + "PatchOrganizationSecurityPolicyRequest", "PatchPacketMirroringRequest", "PatchPacketMirroringRuleNetworkFirewallPolicyRequest", "PatchPerInstanceConfigsInstanceGroupManagerRequest", @@ -2774,6 +2829,7 @@ "PatchRouterRequest", "PatchRuleFirewallPolicyRequest", "PatchRuleNetworkFirewallPolicyRequest", + "PatchRuleOrganizationSecurityPolicyRequest", "PatchRuleRegionNetworkFirewallPolicyRequest", "PatchRuleRegionSecurityPolicyRequest", "PatchRuleSecurityPolicyRequest", @@ -2800,6 +2856,12 @@ "PreservedStatePreservedDisk", "PreservedStatePreservedNetworkIp", "PreservedStatePreservedNetworkIpIpAddress", + "PreviewFeature", + "PreviewFeatureList", + "PreviewFeatureRolloutOperation", + "PreviewFeatureRolloutOperationRolloutInput", + "PreviewFeatureStatus", + "PreviewFeatureStatusReleaseStatus", "PreviewRouterRequest", "Project", "ProjectsDisableXpnResourceRequest", @@ -2864,6 +2926,7 @@ "RegionUrlMapsValidateRequest", "RemoveAssociationFirewallPolicyRequest", "RemoveAssociationNetworkFirewallPolicyRequest", + "RemoveAssociationOrganizationSecurityPolicyRequest", "RemoveAssociationRegionNetworkFirewallPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstancesInstanceGroupRequest", @@ -2875,9 +2938,11 @@ "RemoveResourcePoliciesRegionDiskRequest", "RemoveRuleFirewallPolicyRequest", "RemoveRuleNetworkFirewallPolicyRequest", + "RemoveRuleOrganizationSecurityPolicyRequest", "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "ReportFaultyReservationSubBlockRequest", "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "RequestRemovePeeringNetworkRequest", @@ -2902,6 +2967,8 @@ "ReservationSubBlockPhysicalTopology", "ReservationSubBlocksGetResponse", "ReservationSubBlocksListResponse", + "ReservationSubBlocksReportFaultyRequest", + "ReservationSubBlocksReportFaultyRequestFaultReason", "ResetInstanceRequest", "ResizeDiskRequest", "ResizeInstanceGroupManagerRequest", @@ -2987,6 +3054,7 @@ "SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfigThresholdConfigTrafficGranularityConfig", "SecurityPolicyAdvancedOptionsConfig", "SecurityPolicyAdvancedOptionsConfigJsonCustomConfig", + "SecurityPolicyAssociation", "SecurityPolicyDdosProtectionConfig", "SecurityPolicyList", "SecurityPolicyRecaptchaOptionsConfig", @@ -3128,6 +3196,7 @@ "SimulateMaintenanceEventNodeGroupRequest", "Snapshot", "SnapshotList", + "SnapshotParams", "SnapshotSettings", "SnapshotSettingsStorageLocationSettings", "SnapshotSettingsStorageLocationSettingsStorageLocationPreference", @@ -3295,6 +3364,7 @@ "UpdatePeeringNetworkRequest", "UpdatePerInstanceConfigsInstanceGroupManagerRequest", "UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest", + "UpdatePreviewFeatureRequest", "UpdateRegionAutoscalerRequest", "UpdateRegionBackendServiceRequest", "UpdateRegionCommitmentRequest", 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 5de12110557a..ce747a392c77 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 @@ -36,6 +36,7 @@ "AddAccessConfigInstanceRequest", "AddAssociationFirewallPolicyRequest", "AddAssociationNetworkFirewallPolicyRequest", + "AddAssociationOrganizationSecurityPolicyRequest", "AddAssociationRegionNetworkFirewallPolicyRequest", "AddHealthCheckTargetPoolRequest", "AddInstanceTargetPoolRequest", @@ -49,6 +50,7 @@ "AddResourcePoliciesRegionDiskRequest", "AddRuleFirewallPolicyRequest", "AddRuleNetworkFirewallPolicyRequest", + "AddRuleOrganizationSecurityPolicyRequest", "AddRuleRegionNetworkFirewallPolicyRequest", "AddRuleRegionSecurityPolicyRequest", "AddRuleSecurityPolicyRequest", @@ -209,6 +211,7 @@ "ConnectionDraining", "ConsistentHashLoadBalancerSettings", "ConsistentHashLoadBalancerSettingsHttpCookie", + "CopyRulesOrganizationSecurityPolicyRequest", "CorsPolicy", "CreateInstancesInstanceGroupManagerRequest", "CreateInstancesRegionInstanceGroupManagerRequest", @@ -220,6 +223,7 @@ "CustomerEncryptionKey", "CustomerEncryptionKeyProtectedDisk", "Data", + "Date", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -263,6 +267,7 @@ "DeleteNodeGroupRequest", "DeleteNodeTemplateRequest", "DeleteNodesNodeGroupRequest", + "DeleteOrganizationSecurityPolicyRequest", "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", "DeletePerInstanceConfigsRegionInstanceGroupManagerRequest", @@ -387,6 +392,7 @@ "GetAddressRequest", "GetAssociationFirewallPolicyRequest", "GetAssociationNetworkFirewallPolicyRequest", + "GetAssociationOrganizationSecurityPolicyRequest", "GetAssociationRegionNetworkFirewallPolicyRequest", "GetAutoscalerRequest", "GetBackendBucketRequest", @@ -397,6 +403,8 @@ "GetEffectiveFirewallsInstanceRequest", "GetEffectiveFirewallsNetworkRequest", "GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest", + "GetEffectiveSecurityPoliciesBackendServiceRequest", + "GetEffectiveSecurityPoliciesBackendServiceResponse", "GetExternalVpnGatewayRequest", "GetFirewallPolicyRequest", "GetFirewallRequest", @@ -472,8 +480,10 @@ "GetNodeTypeRequest", "GetOperationalStatusInterconnectAttachmentGroupRequest", "GetOperationalStatusInterconnectGroupRequest", + "GetOrganizationSecurityPolicyRequest", "GetPacketMirroringRequest", "GetPacketMirroringRuleNetworkFirewallPolicyRequest", + "GetPreviewFeatureRequest", "GetProjectRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", @@ -510,6 +520,7 @@ "GetRouterStatusRouterRequest", "GetRuleFirewallPolicyRequest", "GetRuleNetworkFirewallPolicyRequest", + "GetRuleOrganizationSecurityPolicyRequest", "GetRuleRegionNetworkFirewallPolicyRequest", "GetRuleRegionSecurityPolicyRequest", "GetRuleSecurityPolicyRequest", @@ -584,6 +595,7 @@ "Image", "ImageFamilyView", "ImageList", + "ImageParams", "InitialStateConfig", "InsertAddressRequest", "InsertAutoscalerRequest", @@ -619,6 +631,7 @@ "InsertNetworkRequest", "InsertNodeGroupRequest", "InsertNodeTemplateRequest", + "InsertOrganizationSecurityPolicyRequest", "InsertPacketMirroringRequest", "InsertPublicAdvertisedPrefixeRequest", "InsertPublicDelegatedPrefixeRequest", @@ -834,6 +847,7 @@ "ListAcceleratorTypesRequest", "ListAddressesRequest", "ListAssociationsFirewallPolicyRequest", + "ListAssociationsOrganizationSecurityPolicyRequest", "ListAutoscalersRequest", "ListAvailableFeaturesRegionSslPoliciesRequest", "ListAvailableFeaturesSslPoliciesRequest", @@ -888,11 +902,14 @@ "ListNodeTemplatesRequest", "ListNodeTypesRequest", "ListNodesNodeGroupsRequest", + "ListOrganizationSecurityPoliciesRequest", "ListPacketMirroringsRequest", "ListPeeringRoutesNetworksRequest", "ListPerInstanceConfigsInstanceGroupManagersRequest", "ListPerInstanceConfigsRegionInstanceGroupManagersRequest", + "ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest", "ListPreconfiguredExpressionSetsSecurityPoliciesRequest", + "ListPreviewFeaturesRequest", "ListPublicAdvertisedPrefixesRequest", "ListPublicDelegatedPrefixesRequest", "ListReferrersInstancesRequest", @@ -977,6 +994,7 @@ "MoveFirewallPolicyRequest", "MoveGlobalAddressRequest", "MoveInstanceProjectRequest", + "MoveOrganizationSecurityPolicyRequest", "NamedPort", "NatIpInfo", "NatIpInfoNatIpInfoMapping", @@ -1054,6 +1072,7 @@ "OperationAggregatedList", "OperationList", "OperationsScopedList", + "OrganizationSecurityPoliciesListAssociationsResponse", "OutlierDetection", "PacketIntervals", "PacketMirroring", @@ -1087,6 +1106,7 @@ "PatchNetworkFirewallPolicyRequest", "PatchNetworkRequest", "PatchNodeGroupRequest", + "PatchOrganizationSecurityPolicyRequest", "PatchPacketMirroringRequest", "PatchPacketMirroringRuleNetworkFirewallPolicyRequest", "PatchPerInstanceConfigsInstanceGroupManagerRequest", @@ -1108,6 +1128,7 @@ "PatchRouterRequest", "PatchRuleFirewallPolicyRequest", "PatchRuleNetworkFirewallPolicyRequest", + "PatchRuleOrganizationSecurityPolicyRequest", "PatchRuleRegionNetworkFirewallPolicyRequest", "PatchRuleRegionSecurityPolicyRequest", "PatchRuleSecurityPolicyRequest", @@ -1134,6 +1155,12 @@ "PreservedStatePreservedDisk", "PreservedStatePreservedNetworkIp", "PreservedStatePreservedNetworkIpIpAddress", + "PreviewFeature", + "PreviewFeatureList", + "PreviewFeatureRolloutOperation", + "PreviewFeatureRolloutOperationRolloutInput", + "PreviewFeatureStatus", + "PreviewFeatureStatusReleaseStatus", "PreviewRouterRequest", "Project", "ProjectsDisableXpnResourceRequest", @@ -1198,6 +1225,7 @@ "RegionUrlMapsValidateRequest", "RemoveAssociationFirewallPolicyRequest", "RemoveAssociationNetworkFirewallPolicyRequest", + "RemoveAssociationOrganizationSecurityPolicyRequest", "RemoveAssociationRegionNetworkFirewallPolicyRequest", "RemoveHealthCheckTargetPoolRequest", "RemoveInstanceTargetPoolRequest", @@ -1209,9 +1237,11 @@ "RemoveResourcePoliciesRegionDiskRequest", "RemoveRuleFirewallPolicyRequest", "RemoveRuleNetworkFirewallPolicyRequest", + "RemoveRuleOrganizationSecurityPolicyRequest", "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "ReportFaultyReservationSubBlockRequest", "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "RequestRemovePeeringNetworkRequest", @@ -1232,6 +1262,8 @@ "ReservationSubBlockPhysicalTopology", "ReservationSubBlocksGetResponse", "ReservationSubBlocksListResponse", + "ReservationSubBlocksReportFaultyRequest", + "ReservationSubBlocksReportFaultyRequestFaultReason", "ReservationsBlocksPerformMaintenanceRequest", "ReservationsPerformMaintenanceRequest", "ReservationsResizeRequest", @@ -1322,6 +1354,7 @@ "SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfigThresholdConfigTrafficGranularityConfig", "SecurityPolicyAdvancedOptionsConfig", "SecurityPolicyAdvancedOptionsConfigJsonCustomConfig", + "SecurityPolicyAssociation", "SecurityPolicyDdosProtectionConfig", "SecurityPolicyList", "SecurityPolicyRecaptchaOptionsConfig", @@ -1463,6 +1496,7 @@ "SimulateMaintenanceEventNodeGroupRequest", "Snapshot", "SnapshotList", + "SnapshotParams", "SnapshotSettings", "SnapshotSettingsStorageLocationSettings", "SnapshotSettingsStorageLocationSettingsStorageLocationPreference", @@ -1629,6 +1663,7 @@ "UpdatePeeringNetworkRequest", "UpdatePerInstanceConfigsInstanceGroupManagerRequest", "UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest", + "UpdatePreviewFeatureRequest", "UpdateRegionAutoscalerRequest", "UpdateRegionBackendServiceRequest", "UpdateRegionCommitmentRequest", @@ -2639,6 +2674,68 @@ class AddAssociationNetworkFirewallPolicyRequest(proto.Message): ) +class AddAssociationOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for + OrganizationSecurityPolicies.AddAssociation. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + replace_existing_association (bool): + Indicates whether or not to replace it if an + association of the attachment already exists. + This is false by default, in which case an error + will be returned if an association already + exists. + + This field is a member of `oneof`_ ``_replace_existing_association``. + 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``. + security_policy (str): + Name of the security policy to update. + security_policy_association_resource (google.cloud.compute_v1.types.SecurityPolicyAssociation): + The body resource for this request + """ + + replace_existing_association: bool = proto.Field( + proto.BOOL, + number=209541240, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + security_policy_association_resource: "SecurityPolicyAssociation" = proto.Field( + proto.MESSAGE, + number=11761274, + message="SecurityPolicyAssociation", + ) + + class AddAssociationRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.AddAssociation. See the method @@ -3462,6 +3559,54 @@ class AddRuleNetworkFirewallPolicyRequest(proto.Message): ) +class AddRuleOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.AddRule. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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``. + security_policy (str): + Name of the security policy to update. + security_policy_rule_resource (google.cloud.compute_v1.types.SecurityPolicyRule): + The body resource for this request + """ + + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + security_policy_rule_resource: "SecurityPolicyRule" = proto.Field( + proto.MESSAGE, + number=402693443, + message="SecurityPolicyRule", + ) + + class AddRuleRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.AddRule. See the method description for details. @@ -20872,6 +21017,56 @@ class ConsistentHashLoadBalancerSettingsHttpCookie(proto.Message): ) +class CopyRulesOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.CopyRules. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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``. + security_policy (str): + Name of the security policy to update. + source_security_policy (str): + The security policy from which to copy rules. + + This field is a member of `oneof`_ ``_source_security_policy``. + """ + + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + source_security_policy: str = proto.Field( + proto.STRING, + number=234793709, + optional=True, + ) + + class CorsPolicy(proto.Message): r"""The specification for allowing client-side cross-origin requests. For more information about the W3C recommendation for @@ -21523,6 +21718,58 @@ class Data(proto.Message): ) +class Date(proto.Message): + r"""Represents a whole or partial calendar date, such as a birthday. The + time of day and time zone are either specified elsewhere or are + insignificant. The date is relative to the Gregorian Calendar. This + can represent one of the following: \* A full date, with non-zero + year, month, and day values. \* A month and day, with a zero year + (for example, an anniversary). \* A year on its own, with a zero + month and a zero day. \* A year and month, with a zero day (for + example, a credit card expiration date). Related types: \* + google.type.TimeOfDay \* google.type.DateTime \* + google.protobuf.Timestamp + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + day (int): + Day of a month. Must be from 1 to 31 and + valid for the year and month, or 0 to specify a + year by itself or a year and month where the day + isn't significant. + + This field is a member of `oneof`_ ``_day``. + month (int): + Month of a year. Must be from 1 to 12, or 0 + to specify a year without a month and day. + + This field is a member of `oneof`_ ``_month``. + year (int): + Year of the date. Must be from 1 to 9999, or + 0 to specify a date without a year. + + This field is a member of `oneof`_ ``_year``. + """ + + day: int = proto.Field( + proto.INT32, + number=99228, + optional=True, + ) + month: int = proto.Field( + proto.INT32, + number=104080000, + optional=True, + ) + year: int = proto.Field( + proto.INT32, + number=3704893, + optional=True, + ) + + class DeleteAccessConfigInstanceRequest(proto.Message): r"""A request message for Instances.DeleteAccessConfig. See the method description for details. @@ -23605,6 +23852,47 @@ class DeleteNodesNodeGroupRequest(proto.Message): ) +class DeleteOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.Delete. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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``. + security_policy (str): + Name of the security policy to delete. + """ + + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + + class DeletePacketMirroringRequest(proto.Message): r"""A request message for PacketMirrorings.Delete. See the method description for details. @@ -32097,6 +32385,36 @@ class GetAssociationNetworkFirewallPolicyRequest(proto.Message): ) +class GetAssociationOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for + OrganizationSecurityPolicies.GetAssociation. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The name of the association to get from the + security policy. + + This field is a member of `oneof`_ ``_name``. + security_policy (str): + Name of the security policy to which the + queried rule belongs. + """ + + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + + class GetAssociationRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.GetAssociation. See the method @@ -32367,6 +32685,36 @@ class GetEffectiveFirewallsRegionNetworkFirewallPolicyRequest(proto.Message): ) +class GetEffectiveSecurityPoliciesBackendServiceRequest(proto.Message): + r"""A request message for + BackendServices.GetEffectiveSecurityPolicies. See the method + description for details. + + Attributes: + backend_service (str): + Name of the Backend Service for this request. + project (str): + Project ID for this request. + """ + + backend_service: str = proto.Field( + proto.STRING, + number=306946058, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + + +class GetEffectiveSecurityPoliciesBackendServiceResponse(proto.Message): + r"""A response message for + BackendServices.GetEffectiveSecurityPolicies. See the method + description for details. + + """ + + class GetExternalVpnGatewayRequest(proto.Message): r"""A request message for ExternalVpnGateways.Get. See the method description for details. @@ -34684,6 +35032,21 @@ class GetOperationalStatusInterconnectGroupRequest(proto.Message): ) +class GetOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.Get. See + the method description for details. + + Attributes: + security_policy (str): + Name of the security policy to get. + """ + + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + + class GetPacketMirroringRequest(proto.Message): r"""A request message for PacketMirrorings.Get. See the method description for details. @@ -34748,6 +35111,27 @@ class GetPacketMirroringRuleNetworkFirewallPolicyRequest(proto.Message): ) +class GetPreviewFeatureRequest(proto.Message): + r"""A request message for PreviewFeatures.Get. See the method + description for details. + + Attributes: + preview_feature (str): + Name of the PreviewFeature for this request. + project (str): + Project ID for this request. + """ + + preview_feature: str = proto.Field( + proto.STRING, + number=454999423, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + + class GetProjectRequest(proto.Message): r"""A request message for Projects.Get. See the method description for details. @@ -35788,6 +36172,35 @@ class GetRuleNetworkFirewallPolicyRequest(proto.Message): ) +class GetRuleOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.GetRule. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + priority (int): + The priority of the rule to get from the + security policy. + + This field is a member of `oneof`_ ``_priority``. + security_policy (str): + Name of the security policy to which the + queried rule belongs. + """ + + priority: int = proto.Field( + proto.INT32, + number=445151652, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + + class GetRuleRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.GetRule. See the method description for details. @@ -40227,6 +40640,11 @@ class Image(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + params (google.cloud.compute_v1.types.ImageParams): + Input only. [Input Only] Additional params passed with the + request, but not persisted as part of resource payload. + + This field is a member of `oneof`_ ``_params``. raw_disk (google.cloud.compute_v1.types.RawDisk): The parameters of the raw disk image. @@ -40490,6 +40908,12 @@ class Status(proto.Enum): number=3373707, optional=True, ) + params: "ImageParams" = proto.Field( + proto.MESSAGE, + number=78313862, + optional=True, + message="ImageParams", + ) raw_disk: "RawDisk" = proto.Field( proto.MESSAGE, number=503113556, @@ -40676,6 +41100,25 @@ def raw_page(self): ) +class ImageParams(proto.Message): + r"""Additional image params. + + Attributes: + resource_manager_tags (MutableMapping[str, str]): + Resource manager tags to be bound to the image. 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: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=377671164, + ) + + class InitialStateConfig(proto.Message): r"""Initial State for shielded instance, these are public keys which are safe to store in public @@ -42540,6 +42983,60 @@ class InsertNodeTemplateRequest(proto.Message): ) +class InsertOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.Insert. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent_id (str): + Parent ID for this request. The ID can be either be + "folders/[FOLDER_ID]" if the parent is a folder or + "organizations/[ORGANIZATION_ID]" if the parent is an + organization. + + This field is a member of `oneof`_ ``_parent_id``. + 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``. + security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): + The body resource for this request + """ + + parent_id: str = proto.Field( + proto.STRING, + number=459714768, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy_resource: "SecurityPolicy" = proto.Field( + proto.MESSAGE, + number=216159612, + message="SecurityPolicy", + ) + + class InsertPacketMirroringRequest(proto.Message): r"""A request message for PacketMirrorings.Insert. See the method description for details. @@ -51139,6 +51636,13 @@ class Interconnect(proto.Message): possible values. This field is a member of `oneof`_ ``_state``. + subzone (str): + Specific subzone in the InterconnectLocation + that represents where this connection is to be + provisioned. Check the Subzone enum for the list + of possible values. + + This field is a member of `oneof`_ ``_subzone``. """ class AvailableFeatures(proto.Enum): @@ -51268,6 +51772,23 @@ class State(proto.Enum): ACTIVE = 314733318 UNPROVISIONED = 517333979 + class Subzone(proto.Enum): + r"""Specific subzone in the InterconnectLocation that represents + where this connection is to be provisioned. + + Values: + UNDEFINED_SUBZONE (0): + A value indicating that the enum field is not + set. + SUBZONE_A (291575438): + Subzone A. + SUBZONE_B (291575439): + Subzone B. + """ + UNDEFINED_SUBZONE = 0 + SUBZONE_A = 291575438 + SUBZONE_B = 291575439 + aai_enabled: bool = proto.Field( proto.BOOL, number=388780363, @@ -51435,6 +51956,11 @@ class State(proto.Enum): number=109757585, optional=True, ) + subzone: str = proto.Field( + proto.STRING, + number=280084972, + optional=True, + ) class InterconnectApplicationAwareInterconnect(proto.Message): @@ -57559,140 +58085,163 @@ class ListAssociationsFirewallPolicyRequest(proto.Message): ) -class ListAutoscalersRequest(proto.Message): - r"""A request message for Autoscalers.List. See the method +class ListAssociationsOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for + OrganizationSecurityPolicies.ListAssociations. 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 on - resource 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 - Google RE2 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. + target_resource (str): + The target resource to list associations. It + is an organization, or a folder. - This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone for this request. + This field is a member of `oneof`_ ``_target_resource``. """ - 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( + target_resource: str = proto.Field( proto.STRING, - number=227560217, - ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, + number=467318524, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListAvailableFeaturesRegionSslPoliciesRequest(proto.Message): - r"""A request message for - RegionSslPolicies.ListAvailableFeatures. See the method +class ListAutoscalersRequest(proto.Message): + r"""A request message for Autoscalers.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 on + resource 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 + Google RE2 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): + 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 ListAvailableFeaturesRegionSslPoliciesRequest(proto.Message): + r"""A request message for + RegionSslPolicies.ListAvailableFeatures. See the method description for details. @@ -64720,6 +65269,134 @@ class ListNodesNodeGroupsRequest(proto.Message): ) +class ListOrganizationSecurityPoliciesRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.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 on + resource 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 + Google RE2 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``. + parent_id (str): + Parent ID for this request. + + This field is a member of `oneof`_ ``_parent_id``. + 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, + ) + parent_id: str = proto.Field( + proto.STRING, + number=459714768, + optional=True, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + class ListPacketMirroringsRequest(proto.Message): r"""A request message for PacketMirrorings.List. See the method description for details. @@ -65311,10 +65988,10 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): ) -class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): +class ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest(proto.Message): r"""A request message for - SecurityPolicies.ListPreconfiguredExpressionSets. See the method - description for details. + OrganizationSecurityPolicies.ListPreconfiguredExpressionSets. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -65392,133 +66069,10 @@ class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): 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 ListPublicAdvertisedPrefixesRequest(proto.Message): - r"""A request message for PublicAdvertisedPrefixes.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 on - resource 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 - Google RE2 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. + parent_id (str): + Parent ID for this request. - This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. + This field is a member of `oneof`_ ``_parent_id``. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -65551,9 +66105,10 @@ class ListPublicAdvertisedPrefixesRequest(proto.Message): number=19994697, optional=True, ) - project: str = proto.Field( + parent_id: str = proto.Field( proto.STRING, - number=227560217, + number=459714768, + optional=True, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -65562,9 +66117,10 @@ class ListPublicAdvertisedPrefixesRequest(proto.Message): ) -class ListPublicDelegatedPrefixesRequest(proto.Message): - r"""A request message for PublicDelegatedPrefixes.List. See the - method description for details. +class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): + r"""A request message for + SecurityPolicies.ListPreconfiguredExpressionSets. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -65644,8 +66200,6 @@ class ListPublicDelegatedPrefixesRequest(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 @@ -65682,10 +66236,6 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -65693,8 +66243,8 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): ) -class ListReferrersInstancesRequest(proto.Message): - r"""A request message for Instances.ListReferrers. See the method +class ListPreviewFeaturesRequest(proto.Message): + r"""A request message for PreviewFeatures.List. See the method description for details. @@ -65745,10 +66295,6 @@ class ListReferrersInstancesRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. - instance (str): - Name of the target instance scoping this - request, or '-' if the request should span over - all instances in the container. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -65789,8 +66335,6 @@ class ListReferrersInstancesRequest(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( @@ -65798,10 +66342,6 @@ class ListReferrersInstancesRequest(proto.Message): number=336120696, optional=True, ) - instance: str = proto.Field( - proto.STRING, - number=18257045, - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -65826,15 +66366,11 @@ class ListReferrersInstancesRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListRegionAutoscalersRequest(proto.Message): - r"""A request message for RegionAutoscalers.List. See the method - description for details. +class ListPublicAdvertisedPrefixesRequest(proto.Message): + r"""A request message for PublicAdvertisedPrefixes.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -65914,8 +66450,6 @@ class ListRegionAutoscalersRequest(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 @@ -65952,10 +66486,6 @@ class ListRegionAutoscalersRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -65963,8 +66493,8 @@ class ListRegionAutoscalersRequest(proto.Message): ) -class ListRegionBackendServicesRequest(proto.Message): - r"""A request message for RegionBackendServices.List. See the +class ListPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.List. See the method description for details. @@ -66046,7 +66576,7 @@ class ListRegionBackendServicesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + 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 @@ -66094,8 +66624,8 @@ class ListRegionBackendServicesRequest(proto.Message): ) -class ListRegionCommitmentsRequest(proto.Message): - r"""A request message for RegionCommitments.List. See the method +class ListReferrersInstancesRequest(proto.Message): + r"""A request message for Instances.ListReferrers. See the method description for details. @@ -66146,6 +66676,10 @@ class ListRegionCommitmentsRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. + instance (str): + Name of the target instance scoping this + request, or '-' if the request should span over + all instances in the container. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -66176,8 +66710,6 @@ class ListRegionCommitmentsRequest(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 @@ -66188,6 +66720,8 @@ class ListRegionCommitmentsRequest(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( @@ -66195,6 +66729,10 @@ class ListRegionCommitmentsRequest(proto.Message): number=336120696, optional=True, ) + instance: str = proto.Field( + proto.STRING, + number=18257045, + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -66214,19 +66752,19 @@ class ListRegionCommitmentsRequest(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 ListRegionDiskTypesRequest(proto.Message): - r"""A request message for RegionDiskTypes.List. See the method +class ListRegionAutoscalersRequest(proto.Message): + r"""A request message for RegionAutoscalers.List. See the method description for details. @@ -66308,7 +66846,7 @@ class ListRegionDiskTypesRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the region for this request. + 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 @@ -66356,9 +66894,9 @@ class ListRegionDiskTypesRequest(proto.Message): ) -class ListRegionDisksRequest(proto.Message): - r"""A request message for RegionDisks.List. See the method - description for details. +class ListRegionBackendServicesRequest(proto.Message): + r"""A request message for RegionBackendServices.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -66439,7 +66977,7 @@ class ListRegionDisksRequest(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. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -66487,9 +67025,9 @@ class ListRegionDisksRequest(proto.Message): ) -class ListRegionHealthCheckServicesRequest(proto.Message): - r"""A request message for RegionHealthCheckServices.List. See the - method description for details. +class ListRegionCommitmentsRequest(proto.Message): + r"""A request message for RegionCommitments.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -66570,7 +67108,7 @@ class ListRegionHealthCheckServicesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + 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 @@ -66618,8 +67156,8 @@ class ListRegionHealthCheckServicesRequest(proto.Message): ) -class ListRegionHealthChecksRequest(proto.Message): - r"""A request message for RegionHealthChecks.List. See the method +class ListRegionDiskTypesRequest(proto.Message): + r"""A request message for RegionDiskTypes.List. See the method description for details. @@ -66701,7 +67239,7 @@ class ListRegionHealthChecksRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + The 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 @@ -66749,9 +67287,9 @@ class ListRegionHealthChecksRequest(proto.Message): ) -class ListRegionInstanceGroupManagersRequest(proto.Message): - r"""A request message for RegionInstanceGroupManagers.List. See - the method description for details. +class ListRegionDisksRequest(proto.Message): + r"""A request message for RegionDisks.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -66832,7 +67370,7 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + 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 @@ -66880,8 +67418,8 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): ) -class ListRegionInstanceGroupsRequest(proto.Message): - r"""A request message for RegionInstanceGroups.List. See the +class ListRegionHealthCheckServicesRequest(proto.Message): + r"""A request message for RegionHealthCheckServices.List. See the method description for details. @@ -67011,9 +67549,9 @@ class ListRegionInstanceGroupsRequest(proto.Message): ) -class ListRegionInstanceTemplatesRequest(proto.Message): - r"""A request message for RegionInstanceTemplates.List. See the - method description for details. +class ListRegionHealthChecksRequest(proto.Message): + r"""A request message for RegionHealthChecks.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -67094,7 +67632,7 @@ class ListRegionInstanceTemplatesRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the regions for this request. + 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 @@ -67142,9 +67680,9 @@ class ListRegionInstanceTemplatesRequest(proto.Message): ) -class ListRegionInstantSnapshotsRequest(proto.Message): - r"""A request message for RegionInstantSnapshots.List. See the - method description for details. +class ListRegionInstanceGroupManagersRequest(proto.Message): + r"""A request message for RegionInstanceGroupManagers.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -67225,7 +67763,7 @@ class ListRegionInstantSnapshotsRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the region for this request. + 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 @@ -67273,9 +67811,9 @@ class ListRegionInstantSnapshotsRequest(proto.Message): ) -class ListRegionNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for RegionNetworkEndpointGroups.List. See - the method description for details. +class ListRegionInstanceGroupsRequest(proto.Message): + r"""A request message for RegionInstanceGroups.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -67356,9 +67894,7 @@ class ListRegionNetworkEndpointGroupsRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the region where the network - endpoint group is located. It should comply with - RFC1035. + 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 @@ -67406,9 +67942,9 @@ class ListRegionNetworkEndpointGroupsRequest(proto.Message): ) -class ListRegionNetworkFirewallPoliciesRequest(proto.Message): - r"""A request message for RegionNetworkFirewallPolicies.List. See - the method description for details. +class ListRegionInstanceTemplatesRequest(proto.Message): + r"""A request message for RegionInstanceTemplates.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -67489,7 +68025,7 @@ class ListRegionNetworkFirewallPoliciesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + The name of the regions for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -67537,9 +68073,9 @@ class ListRegionNetworkFirewallPoliciesRequest(proto.Message): ) -class ListRegionNotificationEndpointsRequest(proto.Message): - r"""A request message for RegionNotificationEndpoints.List. See - the method description for details. +class ListRegionInstantSnapshotsRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -67620,7 +68156,7 @@ class ListRegionNotificationEndpointsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + The 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 @@ -67668,9 +68204,9 @@ class ListRegionNotificationEndpointsRequest(proto.Message): ) -class ListRegionOperationsRequest(proto.Message): - r"""A request message for RegionOperations.List. See the method - description for details. +class ListRegionNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for RegionNetworkEndpointGroups.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -67751,7 +68287,9 @@ class ListRegionOperationsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + The name of the region where the network + endpoint group is located. It should comply with + RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -67799,9 +68337,9 @@ class ListRegionOperationsRequest(proto.Message): ) -class ListRegionSecurityPoliciesRequest(proto.Message): - r"""A request message for RegionSecurityPolicies.List. See the - method description for details. +class ListRegionNetworkFirewallPoliciesRequest(proto.Message): + r"""A request message for RegionNetworkFirewallPolicies.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -67930,9 +68468,9 @@ class ListRegionSecurityPoliciesRequest(proto.Message): ) -class ListRegionSslCertificatesRequest(proto.Message): - r"""A request message for RegionSslCertificates.List. See the - method description for details. +class ListRegionNotificationEndpointsRequest(proto.Message): + r"""A request message for RegionNotificationEndpoints.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -68061,8 +68599,8 @@ class ListRegionSslCertificatesRequest(proto.Message): ) -class ListRegionSslPoliciesRequest(proto.Message): - r"""A request message for RegionSslPolicies.List. See the method +class ListRegionOperationsRequest(proto.Message): + r"""A request message for RegionOperations.List. See the method description for details. @@ -68144,7 +68682,7 @@ class ListRegionSslPoliciesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + 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 @@ -68192,8 +68730,8 @@ class ListRegionSslPoliciesRequest(proto.Message): ) -class ListRegionTargetHttpProxiesRequest(proto.Message): - r"""A request message for RegionTargetHttpProxies.List. See the +class ListRegionSecurityPoliciesRequest(proto.Message): + r"""A request message for RegionSecurityPolicies.List. See the method description for details. @@ -68323,8 +68861,8 @@ class ListRegionTargetHttpProxiesRequest(proto.Message): ) -class ListRegionTargetHttpsProxiesRequest(proto.Message): - r"""A request message for RegionTargetHttpsProxies.List. See the +class ListRegionSslCertificatesRequest(proto.Message): + r"""A request message for RegionSslCertificates.List. See the method description for details. @@ -68454,9 +68992,9 @@ class ListRegionTargetHttpsProxiesRequest(proto.Message): ) -class ListRegionTargetTcpProxiesRequest(proto.Message): - r"""A request message for RegionTargetTcpProxies.List. See the - method description for details. +class ListRegionSslPoliciesRequest(proto.Message): + r"""A request message for RegionSslPolicies.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -68585,9 +69123,9 @@ class ListRegionTargetTcpProxiesRequest(proto.Message): ) -class ListRegionUrlMapsRequest(proto.Message): - r"""A request message for RegionUrlMaps.List. See the method - description for details. +class ListRegionTargetHttpProxiesRequest(proto.Message): + r"""A request message for RegionTargetHttpProxies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -68716,9 +69254,9 @@ class ListRegionUrlMapsRequest(proto.Message): ) -class ListRegionZonesRequest(proto.Message): - r"""A request message for RegionZones.List. See the method - description for details. +class ListRegionTargetHttpsProxiesRequest(proto.Message): + r"""A request message for RegionTargetHttpsProxies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -68799,7 +69337,7 @@ class ListRegionZonesRequest(proto.Message): project (str): Project ID for this request. region (str): - Region for this request. + 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 @@ -68847,9 +69385,9 @@ class ListRegionZonesRequest(proto.Message): ) -class ListRegionsRequest(proto.Message): - r"""A request message for Regions.List. See the method - description for details. +class ListRegionTargetTcpProxiesRequest(proto.Message): + r"""A request message for RegionTargetTcpProxies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -68929,6 +69467,8 @@ class ListRegionsRequest(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 @@ -68965,6 +69505,10 @@ class ListRegionsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -68972,8 +69516,8 @@ class ListRegionsRequest(proto.Message): ) -class ListReservationBlocksRequest(proto.Message): - r"""A request message for ReservationBlocks.List. See the method +class ListRegionUrlMapsRequest(proto.Message): + r"""A request message for RegionUrlMaps.List. See the method description for details. @@ -69054,9 +69598,8 @@ class ListReservationBlocksRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - reservation (str): - The name of the reservation. Name should - conform to RFC1035 or be a resource ID. + 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 @@ -69067,9 +69610,6 @@ class ListReservationBlocksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone for this request. Zone name - should conform to RFC1035. """ filter: str = proto.Field( @@ -69096,24 +69636,20 @@ class ListReservationBlocksRequest(proto.Message): proto.STRING, number=227560217, ) - reservation: str = proto.Field( + region: str = proto.Field( proto.STRING, - number=47530956, + number=138946292, ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListReservationSubBlocksRequest(proto.Message): - r"""A request message for ReservationSubBlocks.List. See the - method description for details. +class ListRegionZonesRequest(proto.Message): + r"""A request message for RegionZones.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -69191,12 +69727,10 @@ class ListReservationSubBlocksRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - parent_name (str): - The name of the parent reservation and parent block. In the - format of - reservations/{reservation_name}/reservationBlocks/{reservation_block_name} project (str): Project ID for this request. + region (str): + Region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -69207,9 +69741,6 @@ class ListReservationSubBlocksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone for this request. Zone name - should conform to RFC1035. """ filter: str = proto.Field( @@ -69232,27 +69763,23 @@ class ListReservationSubBlocksRequest(proto.Message): number=19994697, optional=True, ) - parent_name: str = proto.Field( - proto.STRING, - number=478151936, - ) 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, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListReservationsRequest(proto.Message): - r"""A request message for Reservations.List. See the method +class ListRegionsRequest(proto.Message): + r"""A request message for Regions.List. See the method description for details. @@ -69343,8 +69870,6 @@ class ListReservationsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone for this request. """ filter: str = proto.Field( @@ -69376,14 +69901,10 @@ class ListReservationsRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListResourcePoliciesRequest(proto.Message): - r"""A request message for ResourcePolicies.List. See the method +class ListReservationBlocksRequest(proto.Message): + r"""A request message for ReservationBlocks.List. See the method description for details. @@ -69464,8 +69985,9 @@ class ListResourcePoliciesRequest(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. + reservation (str): + The name of the reservation. Name should + conform to RFC1035 or be a resource ID. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -69476,6 +69998,9 @@ class ListResourcePoliciesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. """ filter: str = proto.Field( @@ -69502,19 +70027,23 @@ class ListResourcePoliciesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( + reservation: str = proto.Field( proto.STRING, - number=138946292, + number=47530956, ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListRoutePoliciesRoutersRequest(proto.Message): - r"""A request message for Routers.ListRoutePolicies. See the +class ListReservationSubBlocksRequest(proto.Message): + r"""A request message for ReservationSubBlocks.List. See the method description for details. @@ -69593,10 +70122,12 @@ class ListRoutePoliciesRoutersRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. + parent_name (str): + The name of the parent reservation and parent block. In the + format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} 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 @@ -69607,9 +70138,9 @@ 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. + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. """ filter: str = proto.Field( @@ -69632,27 +70163,27 @@ class ListRoutePoliciesRoutersRequest(proto.Message): number=19994697, optional=True, ) - project: str = proto.Field( + parent_name: str = proto.Field( proto.STRING, - number=227560217, + number=478151936, ) - region: str = proto.Field( + project: str = proto.Field( proto.STRING, - number=138946292, + number=227560217, ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - router: str = proto.Field( + zone: str = proto.Field( proto.STRING, - number=148608841, + number=3744684, ) -class ListRoutersRequest(proto.Message): - r"""A request message for Routers.List. See the method +class ListReservationsRequest(proto.Message): + r"""A request message for Reservations.List. See the method description for details. @@ -69733,8 +70264,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 @@ -69745,6 +70274,8 @@ class ListRoutersRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone for this request. """ filter: str = proto.Field( @@ -69771,20 +70302,20 @@ 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, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListRoutesRequest(proto.Message): - r"""A request message for Routes.List. See the method description - for details. +class ListResourcePoliciesRequest(proto.Message): + r"""A request message for ResourcePolicies.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -69864,6 +70395,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 @@ -69900,6 +70433,10 @@ 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, @@ -69907,9 +70444,9 @@ class ListRoutesRequest(proto.Message): ) -class ListSecurityPoliciesRequest(proto.Message): - r"""A request message for SecurityPolicies.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 @@ -69989,6 +70526,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 @@ -69999,6 +70538,9 @@ class ListSecurityPoliciesRequest(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( @@ -70025,15 +70567,23 @@ 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, optional=True, ) + router: str = proto.Field( + proto.STRING, + number=148608841, + ) -class ListServiceAttachmentsRequest(proto.Message): - r"""A request message for ServiceAttachments.List. See the method +class ListRoutersRequest(proto.Message): + r"""A request message for Routers.List. See the method description for details. @@ -70115,7 +70665,7 @@ class ListServiceAttachmentsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region of this request. + 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 @@ -70163,9 +70713,9 @@ class ListServiceAttachmentsRequest(proto.Message): ) -class ListSnapshotsRequest(proto.Message): - r"""A request message for Snapshots.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 @@ -70288,8 +70838,8 @@ class ListSnapshotsRequest(proto.Message): ) -class ListSslCertificatesRequest(proto.Message): - r"""A request message for SslCertificates.List. See the method +class ListSecurityPoliciesRequest(proto.Message): + r"""A request message for SecurityPolicies.List. See the method description for details. @@ -70413,8 +70963,8 @@ class ListSslCertificatesRequest(proto.Message): ) -class ListSslPoliciesRequest(proto.Message): - r"""A request message for SslPolicies.List. See the method +class ListServiceAttachmentsRequest(proto.Message): + r"""A request message for ServiceAttachments.List. See the method description for details. @@ -70495,6 +71045,8 @@ class ListSslPoliciesRequest(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 @@ -70531,6 +71083,10 @@ class ListSslPoliciesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -70538,8 +71094,8 @@ class ListSslPoliciesRequest(proto.Message): ) -class ListStoragePoolTypesRequest(proto.Message): - r"""A request message for StoragePoolTypes.List. See the method +class ListSnapshotsRequest(proto.Message): + r"""A request message for Snapshots.List. See the method description for details. @@ -70630,8 +71186,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( @@ -70663,14 +71217,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 ListSslCertificatesRequest(proto.Message): + r"""A request message for SslCertificates.List. See the method description for details. @@ -70761,8 +71311,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( @@ -70794,14 +71342,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 ListSslPoliciesRequest(proto.Message): + r"""A request message for SslPolicies.List. See the method description for details. @@ -70882,8 +71426,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 @@ -70894,33 +71436,8 @@ 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: - 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, @@ -70945,24 +71462,146 @@ class Views(proto.Enum): proto.STRING, number=227560217, ) - region: str = proto.Field( + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListStoragePoolTypesRequest(proto.Message): + r"""A request message for StoragePoolTypes.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 on + resource 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 + Google RE2 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, - number=138946292, + 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, ) - 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 ListStoragePoolsRequest(proto.Message): + r"""A request message for StoragePools.List. See the method description for details. @@ -71053,6 +71692,8 @@ class ListTargetGrpcProxiesRequest(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( @@ -71084,10 +71725,14 @@ class ListTargetGrpcProxiesRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListTargetHttpProxiesRequest(proto.Message): - r"""A request message for TargetHttpProxies.List. See the method +class ListSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.List. See the method description for details. @@ -71168,6 +71813,8 @@ class ListTargetHttpProxiesRequest(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 @@ -71178,8 +71825,33 @@ class ListTargetHttpProxiesRequest(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, @@ -71204,15 +71876,24 @@ class ListTargetHttpProxiesRequest(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 ListTargetHttpsProxiesRequest(proto.Message): - r"""A request message for TargetHttpsProxies.List. See the method +class ListTargetGrpcProxiesRequest(proto.Message): + r"""A request message for TargetGrpcProxies.List. See the method description for details. @@ -71336,8 +72017,8 @@ class ListTargetHttpsProxiesRequest(proto.Message): ) -class ListTargetInstancesRequest(proto.Message): - r"""A request message for TargetInstances.List. See the method +class ListTargetHttpProxiesRequest(proto.Message): + r"""A request message for TargetHttpProxies.List. See the method description for details. @@ -71428,8 +72109,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( @@ -71461,14 +72140,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 ListTargetHttpsProxiesRequest(proto.Message): + r"""A request message for TargetHttpsProxies.List. See the method description for details. @@ -71549,8 +72224,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 @@ -71587,10 +72260,6 @@ 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, @@ -71598,8 +72267,8 @@ class ListTargetPoolsRequest(proto.Message): ) -class ListTargetSslProxiesRequest(proto.Message): - r"""A request message for TargetSslProxies.List. See the method +class ListTargetInstancesRequest(proto.Message): + r"""A request message for TargetInstances.List. See the method description for details. @@ -71690,6 +72359,8 @@ class ListTargetSslProxiesRequest(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( @@ -71721,10 +72392,14 @@ class ListTargetSslProxiesRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListTargetTcpProxiesRequest(proto.Message): - r"""A request message for TargetTcpProxies.List. See the method +class ListTargetPoolsRequest(proto.Message): + r"""A request message for TargetPools.List. See the method description for details. @@ -71805,6 +72480,8 @@ class ListTargetTcpProxiesRequest(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 @@ -71841,6 +72518,10 @@ class ListTargetTcpProxiesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -71848,8 +72529,8 @@ class ListTargetTcpProxiesRequest(proto.Message): ) -class ListTargetVpnGatewaysRequest(proto.Message): - r"""A request message for TargetVpnGateways.List. See the method +class ListTargetSslProxiesRequest(proto.Message): + r"""A request message for TargetSslProxies.List. See the method description for details. @@ -71930,8 +72611,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 @@ -71968,10 +72647,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, @@ -71979,8 +72654,8 @@ class ListTargetVpnGatewaysRequest(proto.Message): ) -class ListUrlMapsRequest(proto.Message): - r"""A request message for UrlMaps.List. See the method +class ListTargetTcpProxiesRequest(proto.Message): + r"""A request message for TargetTcpProxies.List. See the method description for details. @@ -72104,9 +72779,9 @@ class ListUrlMapsRequest(proto.Message): ) -class ListUsableBackendServicesRequest(proto.Message): - r"""A request message for BackendServices.ListUsable. See the - method description for details. +class ListTargetVpnGatewaysRequest(proto.Message): + r"""A request message for TargetVpnGateways.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -72186,6 +72861,8 @@ class ListUsableBackendServicesRequest(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 @@ -72222,6 +72899,10 @@ class ListUsableBackendServicesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -72229,9 +72910,9 @@ class ListUsableBackendServicesRequest(proto.Message): ) -class ListUsableRegionBackendServicesRequest(proto.Message): - r"""A request message for RegionBackendServices.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 @@ -72311,10 +72992,6 @@ class ListUsableRegionBackendServicesRequest(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 @@ -72351,10 +73028,6 @@ class ListUsableRegionBackendServicesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -72362,9 +73035,9 @@ class ListUsableRegionBackendServicesRequest(proto.Message): ) -class ListUsableSubnetworksRequest(proto.Message): - r"""A request message for Subnetworks.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 @@ -72454,13 +73127,6 @@ class ListUsableSubnetworksRequest(proto.Message): 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( @@ -72492,16 +73158,11 @@ class ListUsableSubnetworksRequest(proto.Message): 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 @@ -72582,7 +73243,9 @@ 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 @@ -72630,8 +73293,145 @@ class ListVpnGatewaysRequest(proto.Message): ) -class ListVpnTunnelsRequest(proto.Message): - r"""A request message for VpnTunnels.List. See the method +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 on + resource 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 + Google RE2 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. @@ -72761,8 +73561,8 @@ class ListVpnTunnelsRequest(proto.Message): ) -class ListXpnHostsProjectsRequest(proto.Message): - r"""A request message for Projects.ListXpnHosts. See the method +class ListVpnTunnelsRequest(proto.Message): + r"""A request message for VpnTunnels.List. See the method description for details. @@ -72843,8 +73643,139 @@ class ListXpnHostsProjectsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - projects_list_xpn_hosts_request_resource (google.cloud.compute_v1.types.ProjectsListXpnHostsRequest): - The body resource 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 + 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 ListXpnHostsProjectsRequest(proto.Message): + r"""A request message for Projects.ListXpnHosts. 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 on + resource 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 + Google RE2 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. + projects_list_xpn_hosts_request_resource (google.cloud.compute_v1.types.ProjectsListXpnHostsRequest): + The body resource for this request return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -74961,6 +75892,56 @@ class MoveInstanceProjectRequest(proto.Message): ) +class MoveOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.Move. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent_id (str): + The new parent of the security policy. + + This field is a member of `oneof`_ ``_parent_id``. + 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``. + security_policy (str): + Name of the security policy to update. + """ + + parent_id: str = proto.Field( + proto.STRING, + number=459714768, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + + class NamedPort(proto.Message): r"""The named port. For example: <"http", 80>. @@ -82197,6 +83178,34 @@ class OperationsScopedList(proto.Message): ) +class OrganizationSecurityPoliciesListAssociationsResponse(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + associations (MutableSequence[google.cloud.compute_v1.types.SecurityPolicyAssociation]): + A list of associations. + kind (str): + [Output Only] Type of securityPolicy associations. Always + compute#organizationSecurityPoliciesListAssociations for + lists of securityPolicy associations. + + This field is a member of `oneof`_ ``_kind``. + """ + + associations: MutableSequence["SecurityPolicyAssociation"] = proto.RepeatedField( + proto.MESSAGE, + number=508736530, + message="SecurityPolicyAssociation", + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + + class OutlierDetection(proto.Message): r"""Settings controlling the eviction of unhealthy hosts from the load balancing pool for the backend service. @@ -84319,6 +85328,54 @@ class PatchNodeGroupRequest(proto.Message): ) +class PatchOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.Patch. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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``. + security_policy (str): + Name of the security policy to update. + security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): + The body resource for this request + """ + + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + security_policy_resource: "SecurityPolicy" = proto.Field( + proto.MESSAGE, + number=216159612, + message="SecurityPolicy", + ) + + class PatchPacketMirroringRequest(proto.Message): r"""A request message for PacketMirrorings.Patch. See the method description for details. @@ -85603,6 +86660,63 @@ class PatchRuleNetworkFirewallPolicyRequest(proto.Message): ) +class PatchRuleOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.PatchRule. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + priority (int): + The priority of the rule to patch. + + This field is a member of `oneof`_ ``_priority``. + 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``. + security_policy (str): + Name of the security policy to update. + security_policy_rule_resource (google.cloud.compute_v1.types.SecurityPolicyRule): + The body resource for this request + """ + + priority: int = proto.Field( + proto.INT32, + number=445151652, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + security_policy_rule_resource: "SecurityPolicyRule" = proto.Field( + proto.MESSAGE, + number=402693443, + message="SecurityPolicyRule", + ) + + class PatchRuleRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.PatchRule. See the method @@ -87391,6 +88505,365 @@ class PreservedStatePreservedNetworkIpIpAddress(proto.Message): ) +class PreviewFeature(proto.Message): + r"""Represents a single Google Compute Engine preview feature. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + activation_status (str): + Specifies whether the feature is enabled or + disabled. Check the ActivationStatus enum for + the list of possible values. + + This field is a member of `oneof`_ ``_activation_status``. + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 text format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + description (str): + [Output Only] Description of the feature. + + This field is a member of `oneof`_ ``_description``. + id (int): + [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] The type of the feature. Always + "compute#previewFeature" for preview features. + + This field is a member of `oneof`_ ``_kind``. + name (str): + Name of the feature. + + This field is a member of `oneof`_ ``_name``. + rollout_operation (google.cloud.compute_v1.types.PreviewFeatureRolloutOperation): + Rollout operation of the feature. + + This field is a member of `oneof`_ ``_rollout_operation``. + self_link (str): + [Output Only] Server-defined URL for the resource. + + This field is a member of `oneof`_ ``_self_link``. + status (google.cloud.compute_v1.types.PreviewFeatureStatus): + [Output only] Status of the feature. + + This field is a member of `oneof`_ ``_status``. + """ + + class ActivationStatus(proto.Enum): + r"""Specifies whether the feature is enabled or disabled. + + Values: + UNDEFINED_ACTIVATION_STATUS (0): + A value indicating that the enum field is not + set. + ACTIVATION_STATE_UNSPECIFIED (632160): + No description available. + DISABLED (516696700): + No description available. + ENABLED (182130465): + No description available. + """ + UNDEFINED_ACTIVATION_STATUS = 0 + ACTIVATION_STATE_UNSPECIFIED = 632160 + DISABLED = 516696700 + ENABLED = 182130465 + + activation_status: str = proto.Field( + proto.STRING, + number=71960379, + optional=True, + ) + 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, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + rollout_operation: "PreviewFeatureRolloutOperation" = proto.Field( + proto.MESSAGE, + number=486746201, + optional=True, + message="PreviewFeatureRolloutOperation", + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + status: "PreviewFeatureStatus" = proto.Field( + proto.MESSAGE, + number=181260274, + optional=True, + message="PreviewFeatureStatus", + ) + + +class PreviewFeatureList(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.PreviewFeature]): + A list of PreviewFeature 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 than maxResults, 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] Server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + [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["PreviewFeature"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="PreviewFeature", + ) + 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 PreviewFeatureRolloutOperation(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.PreviewFeatureRolloutOperationRolloutInput): + Input only. The input for the rollout + operation. + + This field is a member of `oneof`_ ``_rollout_input``. + """ + + rollout_input: "PreviewFeatureRolloutOperationRolloutInput" = proto.Field( + proto.MESSAGE, + number=265745340, + optional=True, + message="PreviewFeatureRolloutOperationRolloutInput", + ) + + +class PreviewFeatureRolloutOperationRolloutInput(proto.Message): + r"""Represents the input for the rollout operation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The name of the rollout plan Ex. + organizations//locations/global/rolloutPlans/ + Ex. folders//locations/global/rolloutPlans/ Ex. + projects//locations/global/rolloutPlans/. + + This field is a member of `oneof`_ ``_name``. + predefined_rollout_plan (str): + Predefined rollout plan. + Check the PredefinedRolloutPlan enum for the + list of possible values. + + This field is a member of `oneof`_ ``_predefined_rollout_plan``. + """ + + class PredefinedRolloutPlan(proto.Enum): + r"""Predefined rollout plan. + + Values: + UNDEFINED_PREDEFINED_ROLLOUT_PLAN (0): + A value indicating that the enum field is not + set. + ROLLOUT_PLAN_FAST_ROLLOUT (167808726): + No description available. + ROLLOUT_PLAN_TWO_DAY_ROLLOUT (349866771): + No description available. + ROLLOUT_PLAN_UNSPECIFIED (144511983): + No description available. + """ + UNDEFINED_PREDEFINED_ROLLOUT_PLAN = 0 + ROLLOUT_PLAN_FAST_ROLLOUT = 167808726 + ROLLOUT_PLAN_TWO_DAY_ROLLOUT = 349866771 + ROLLOUT_PLAN_UNSPECIFIED = 144511983 + + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + predefined_rollout_plan: str = proto.Field( + proto.STRING, + number=364023440, + optional=True, + ) + + +class PreviewFeatureStatus(proto.Message): + r"""[Output Only] The status of the feature. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + [Output Only] The description of the feature. + + This field is a member of `oneof`_ ``_description``. + help_link (str): + [Output Only] Link to the public documentation for the + feature. + + This field is a member of `oneof`_ ``_help_link``. + release_status (google.cloud.compute_v1.types.PreviewFeatureStatusReleaseStatus): + + This field is a member of `oneof`_ ``_release_status``. + """ + + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + help_link: str = proto.Field( + proto.STRING, + number=223410744, + optional=True, + ) + release_status: "PreviewFeatureStatusReleaseStatus" = proto.Field( + proto.MESSAGE, + number=508026666, + optional=True, + message="PreviewFeatureStatusReleaseStatus", + ) + + +class PreviewFeatureStatusReleaseStatus(proto.Message): + r"""[Output Only] The release status of the feature. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + stage (str): + [Output Only] The stage of the feature. Check the Stage enum + for the list of possible values. + + This field is a member of `oneof`_ ``_stage``. + update_date (google.cloud.compute_v1.types.Date): + Output only. The last date when a feature + transitioned between ReleaseStatuses. + + This field is a member of `oneof`_ ``_update_date``. + """ + + class Stage(proto.Enum): + r"""[Output Only] The stage of the feature. + + Values: + UNDEFINED_STAGE (0): + A value indicating that the enum field is not + set. + DEPRECATED (463360435): + No description available. + GA (2266): + No description available. + PREVIEW (399798184): + No description available. + STAGE_UNSPECIFIED (63695670): + No description available. + """ + UNDEFINED_STAGE = 0 + DEPRECATED = 463360435 + GA = 2266 + PREVIEW = 399798184 + STAGE_UNSPECIFIED = 63695670 + + stage: str = proto.Field( + proto.STRING, + number=109757182, + optional=True, + ) + update_date: "Date" = proto.Field( + proto.MESSAGE, + number=499811684, + optional=True, + message="Date", + ) + + class PreviewRouterRequest(proto.Message): r"""A request message for Routers.Preview. See the method description for details. @@ -91647,6 +93120,57 @@ class RemoveAssociationNetworkFirewallPolicyRequest(proto.Message): ) +class RemoveAssociationOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for + OrganizationSecurityPolicies.RemoveAssociation. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name for the attachment that will be removed. + + This field is a member of `oneof`_ ``_name``. + 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``. + security_policy (str): + Name of the security policy to update. + """ + + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + + class RemoveAssociationRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.RemoveAssociation. See the method @@ -92298,6 +93822,58 @@ class RemoveRuleNetworkFirewallPolicyRequest(proto.Message): ) +class RemoveRuleOrganizationSecurityPolicyRequest(proto.Message): + r"""A request message for + OrganizationSecurityPolicies.RemoveRule. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + priority (int): + The priority of the rule to remove from the + security policy. + + This field is a member of `oneof`_ ``_priority``. + 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``. + security_policy (str): + Name of the security policy to update. + """ + + priority: int = proto.Field( + proto.INT32, + number=445151652, + optional=True, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + security_policy: str = proto.Field( + proto.STRING, + number=171082513, + ) + + class RemoveRuleRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.RemoveRule. See the method @@ -92436,6 +94012,76 @@ class RemoveRuleSecurityPolicyRequest(proto.Message): ) +class ReportFaultyReservationSubBlockRequest(proto.Message): + r"""A request message for ReservationSubBlocks.ReportFaulty. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent_name (str): + The name of the parent reservation and parent block. In the + format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + 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``. + reservation_sub_block (str): + The name of the reservation subBlock. Name + should conform to RFC1035 or be a resource ID. + reservation_sub_blocks_report_faulty_request_resource (google.cloud.compute_v1.types.ReservationSubBlocksReportFaultyRequest): + The body resource for this request + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. + """ + + parent_name: str = proto.Field( + proto.STRING, + number=478151936, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + reservation_sub_block: str = proto.Field( + proto.STRING, + number=22750491, + ) + reservation_sub_blocks_report_faulty_request_resource: "ReservationSubBlocksReportFaultyRequest" = proto.Field( + proto.MESSAGE, + number=450847938, + message="ReservationSubBlocksReportFaultyRequest", + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class ReportHostAsFaultyInstanceRequest(proto.Message): r"""A request message for Instances.ReportHostAsFaulty. See the method description for details. @@ -94051,6 +95697,136 @@ def raw_page(self): ) +class ReservationSubBlocksReportFaultyRequest(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disruption_schedule (str): + The disruption schedule for the subBlock. + Check the DisruptionSchedule enum for the list + of possible values. + + This field is a member of `oneof`_ ``_disruption_schedule``. + failure_component (str): + The component that experienced the fault. + Check the FailureComponent enum for the list of + possible values. + + This field is a member of `oneof`_ ``_failure_component``. + fault_reasons (MutableSequence[google.cloud.compute_v1.types.ReservationSubBlocksReportFaultyRequestFaultReason]): + The reasons for the fault experienced with + the subBlock. + """ + + class DisruptionSchedule(proto.Enum): + r"""The disruption schedule for the subBlock. + + Values: + UNDEFINED_DISRUPTION_SCHEDULE (0): + A value indicating that the enum field is not + set. + DISRUPTION_SCHEDULE_UNSPECIFIED (332543835): + No description available. + IMMEDIATE (152881041): + All VMs will be disrupted immediately. + """ + UNDEFINED_DISRUPTION_SCHEDULE = 0 + DISRUPTION_SCHEDULE_UNSPECIFIED = 332543835 + IMMEDIATE = 152881041 + + class FailureComponent(proto.Enum): + r"""The component that experienced the fault. + + Values: + UNDEFINED_FAILURE_COMPONENT (0): + A value indicating that the enum field is not + set. + FAILURE_COMPONENT_UNSPECIFIED (332003744): + No description available. + MULTIPLE_FAULTY_HOSTS (423545298): + Multiple hosts experienced the fault. + NVLINK_SWITCH (239107153): + The NVLink switch experienced the fault. + """ + UNDEFINED_FAILURE_COMPONENT = 0 + FAILURE_COMPONENT_UNSPECIFIED = 332003744 + MULTIPLE_FAULTY_HOSTS = 423545298 + NVLINK_SWITCH = 239107153 + + disruption_schedule: str = proto.Field( + proto.STRING, + number=95871619, + optional=True, + ) + failure_component: str = proto.Field( + proto.STRING, + number=25912456, + optional=True, + ) + fault_reasons: MutableSequence[ + "ReservationSubBlocksReportFaultyRequestFaultReason" + ] = proto.RepeatedField( + proto.MESSAGE, + number=168056210, + message="ReservationSubBlocksReportFaultyRequestFaultReason", + ) + + +class ReservationSubBlocksReportFaultyRequestFaultReason(proto.Message): + r"""The reason for the fault experienced with the subBlock. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + behavior (str): + The behavior of the fault experienced with + the subBlock. Check the Behavior enum for the + list of possible values. + + This field is a member of `oneof`_ ``_behavior``. + description (str): + The description of the fault experienced with + the subBlock. + + This field is a member of `oneof`_ ``_description``. + """ + + class Behavior(proto.Enum): + r"""The behavior of the fault experienced with the subBlock. + + Values: + UNDEFINED_BEHAVIOR (0): + A value indicating that the enum field is not + set. + FAULT_BEHAVIOR_UNSPECIFIED (447660743): + No description available. + GPU_ERROR (198817909): + The subBlock experienced a GPU error. + PERFORMANCE (135701520): + The subBlock experienced performance issues. + SWITCH_FAILURE (254909279): + The subBlock experienced a switch failure. + """ + UNDEFINED_BEHAVIOR = 0 + FAULT_BEHAVIOR_UNSPECIFIED = 447660743 + GPU_ERROR = 198817909 + PERFORMANCE = 135701520 + SWITCH_FAILURE = 254909279 + + behavior: str = proto.Field( + proto.STRING, + number=437170770, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + + class ReservationsBlocksPerformMaintenanceRequest(proto.Message): r""" @@ -100613,6 +102389,9 @@ class SecurityPolicy(proto.Message): advanced_options_config (google.cloud.compute_v1.types.SecurityPolicyAdvancedOptionsConfig): This field is a member of `oneof`_ ``_advanced_options_config``. + associations (MutableSequence[google.cloud.compute_v1.types.SecurityPolicyAssociation]): + A list of associations that belong to this + policy. creation_timestamp (str): [Output Only] Creation timestamp in RFC3339 text format. @@ -100701,6 +102480,20 @@ class SecurityPolicy(proto.Message): [Output Only] Server-defined URL for the resource. This field is a member of `oneof`_ ``_self_link``. + short_name (str): + User-provided name of the organization security policy. The + name should be unique in the organization in which the + security policy is created. This should only be used when + SecurityPolicyType is CLOUD_ARMOR. The name must be 1-63 + characters long, and comply with + https://www.ietf.org/rfc/rfc1035.txt. 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`_ ``_short_name``. type_ (str): The type indicates the intended use of the security policy. - CLOUD_ARMOR: Cloud Armor backend security policies can be @@ -100784,6 +102577,11 @@ class Type(proto.Enum): optional=True, message="SecurityPolicyAdvancedOptionsConfig", ) + associations: MutableSequence["SecurityPolicyAssociation"] = proto.RepeatedField( + proto.MESSAGE, + number=508736530, + message="SecurityPolicyAssociation", + ) creation_timestamp: str = proto.Field( proto.STRING, number=30525366, @@ -100851,6 +102649,11 @@ class Type(proto.Enum): number=456214797, optional=True, ) + short_name: str = proto.Field( + proto.STRING, + number=492051566, + optional=True, + ) type_: str = proto.Field( proto.STRING, number=3575610, @@ -101212,6 +103015,78 @@ class SecurityPolicyAdvancedOptionsConfigJsonCustomConfig(proto.Message): ) +class SecurityPolicyAssociation(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + attachment_id (str): + The resource that the security policy is + attached to. + + This field is a member of `oneof`_ ``_attachment_id``. + display_name (str): + [Output Only] The display name of the security policy of the + association. + + This field is a member of `oneof`_ ``_display_name``. + excluded_folders (MutableSequence[str]): + A list of folders to exclude from the + security policy. + excluded_projects (MutableSequence[str]): + A list of projects to exclude from the + security policy. + name (str): + The name for an association. + + This field is a member of `oneof`_ ``_name``. + security_policy_id (str): + [Output Only] The security policy ID of the association. + + This field is a member of `oneof`_ ``_security_policy_id``. + short_name (str): + [Output Only] The short name of the security policy of the + association. + + This field is a member of `oneof`_ ``_short_name``. + """ + + attachment_id: str = proto.Field( + proto.STRING, + number=103768503, + optional=True, + ) + display_name: str = proto.Field( + proto.STRING, + number=4473832, + optional=True, + ) + excluded_folders: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=310611024, + ) + excluded_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=283070287, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + security_policy_id: str = proto.Field( + proto.STRING, + number=203671817, + optional=True, + ) + short_name: str = proto.Field( + proto.STRING, + number=492051566, + optional=True, + ) + + class SecurityPolicyDdosProtectionConfig(proto.Message): r""" @@ -108510,7 +110385,6 @@ class Snapshot(proto.Message): r"""Represents a Persistent Disk Snapshot resource. You can use snapshots to back up data on a regular interval. For more information, read Creating persistent disk snapshots. - LINT.IfChange .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -108633,6 +110507,11 @@ class Snapshot(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + params (google.cloud.compute_v1.types.SnapshotParams): + Input only. [Input Only] Additional params passed with the + request, but not persisted as part of resource payload. + + This field is a member of `oneof`_ ``_params``. satisfies_pzi (bool): Output only. Reserved for future use. @@ -108929,6 +110808,12 @@ class StorageBytesStatus(proto.Enum): number=3373707, optional=True, ) + params: "SnapshotParams" = proto.Field( + proto.MESSAGE, + number=78313862, + optional=True, + message="SnapshotParams", + ) satisfies_pzi: bool = proto.Field( proto.BOOL, number=480964257, @@ -109096,6 +110981,25 @@ def raw_page(self): ) +class SnapshotParams(proto.Message): + r"""Additional snapshot params. + + Attributes: + resource_manager_tags (MutableMapping[str, str]): + Resource manager tags to be bound to the snapshot. 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: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=377671164, + ) + + class SnapshotSettings(proto.Message): r""" @@ -119876,6 +121780,60 @@ class UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest(proto.Message): ) +class UpdatePreviewFeatureRequest(proto.Message): + r"""A request message for PreviewFeatures.Update. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + preview_feature (str): + Name of the PreviewFeature for this request. + preview_feature_resource (google.cloud.compute_v1.types.PreviewFeature): + 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``. + """ + + preview_feature: str = proto.Field( + proto.STRING, + number=454999423, + ) + preview_feature_resource: "PreviewFeature" = proto.Field( + proto.MESSAGE, + number=10876622, + message="PreviewFeature", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + class UpdateRegionAutoscalerRequest(proto.Message): r"""A request message for RegionAutoscalers.Update. See the method description for details. diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_backend_services_get_effective_security_policies_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_backend_services_get_effective_security_policies_sync.py new file mode 100644 index 000000000000..d1cf9277078b --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_backend_services_get_effective_security_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 GetEffectiveSecurityPolicies +# 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_BackendServices_GetEffectiveSecurityPolicies_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_effective_security_policies(): + # Create a client + client = compute_v1.BackendServicesClient() + + # Initialize request argument(s) + request = compute_v1.GetEffectiveSecurityPoliciesBackendServiceRequest( + backend_service="backend_service_value", + project="project_value", + ) + + # Make the request + response = client.get_effective_security_policies(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_BackendServices_GetEffectiveSecurityPolicies_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_add_association_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_add_association_sync.py new file mode 100644 index 000000000000..be52bd45a981 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_add_association_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 AddAssociation +# 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_OrganizationSecurityPolicies_AddAssociation_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_add_association(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.AddAssociationOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.add_association(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_AddAssociation_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_add_rule_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_add_rule_sync.py new file mode 100644 index 000000000000..663ded92c86d --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_add_rule_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 AddRule +# 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_OrganizationSecurityPolicies_AddRule_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_add_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.AddRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.add_rule(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_AddRule_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_copy_rules_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_copy_rules_sync.py new file mode 100644 index 000000000000..9df81d21e197 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_copy_rules_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 CopyRules +# 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_OrganizationSecurityPolicies_CopyRules_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_copy_rules(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.CopyRulesOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.copy_rules(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_CopyRules_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_delete_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_delete_sync.py new file mode 100644 index 000000000000..0ecd03d0bd15 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_delete_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_OrganizationSecurityPolicies_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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.DeleteOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_Delete_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_association_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_association_sync.py new file mode 100644 index 000000000000..052ea8cb155f --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_association_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 GetAssociation +# 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_OrganizationSecurityPolicies_GetAssociation_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_association(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.GetAssociationOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.get_association(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_GetAssociation_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_rule_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_rule_sync.py new file mode 100644 index 000000000000..a032e966361b --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_rule_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 GetRule +# 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_OrganizationSecurityPolicies_GetRule_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_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.GetRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.get_rule(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_GetRule_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_sync.py new file mode 100644 index 000000000000..b1e4ebf73212 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_get_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_OrganizationSecurityPolicies_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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.GetOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_Get_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_insert_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_insert_sync.py new file mode 100644 index 000000000000..acf838cc4ad1 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_insert_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_OrganizationSecurityPolicies_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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.InsertOrganizationSecurityPolicyRequest( + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_Insert_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_associations_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_associations_sync.py new file mode 100644 index 000000000000..226f1d3158da --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_associations_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 ListAssociations +# 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_OrganizationSecurityPolicies_ListAssociations_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_associations(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.ListAssociationsOrganizationSecurityPolicyRequest( + ) + + # Make the request + response = client.list_associations(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_ListAssociations_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py new file mode 100644 index 000000000000..d957bddad4b2 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 ListPreconfiguredExpressionSets +# 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_OrganizationSecurityPolicies_ListPreconfiguredExpressionSets_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_preconfigured_expression_sets(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest( + ) + + # Make the request + response = client.list_preconfigured_expression_sets(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_ListPreconfiguredExpressionSets_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_sync.py new file mode 100644 index 000000000000..fae453ad2b25 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_list_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_OrganizationSecurityPolicies_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.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.ListOrganizationSecurityPoliciesRequest( + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_List_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_move_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_move_sync.py new file mode 100644 index 000000000000..bf3d47569090 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_move_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Move +# 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_OrganizationSecurityPolicies_Move_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_move(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.MoveOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.move(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_Move_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_patch_rule_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_patch_rule_sync.py new file mode 100644 index 000000000000..453658579ffa --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_patch_rule_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 PatchRule +# 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_OrganizationSecurityPolicies_PatchRule_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_patch_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.PatchRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.patch_rule(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_PatchRule_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_patch_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_patch_sync.py new file mode 100644 index 000000000000..c4244ac18952 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_patch_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Patch +# 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_OrganizationSecurityPolicies_Patch_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_patch(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.PatchOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.patch(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_Patch_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_remove_association_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_remove_association_sync.py new file mode 100644 index 000000000000..31f00ff086cd --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_remove_association_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 RemoveAssociation +# 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_OrganizationSecurityPolicies_RemoveAssociation_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_remove_association(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.RemoveAssociationOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.remove_association(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_RemoveAssociation_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_remove_rule_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_remove_rule_sync.py new file mode 100644 index 000000000000..7f299519c381 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_organization_security_policies_remove_rule_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 RemoveRule +# 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_OrganizationSecurityPolicies_RemoveRule_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_remove_rule(): + # Create a client + client = compute_v1.OrganizationSecurityPoliciesClient() + + # Initialize request argument(s) + request = compute_v1.RemoveRuleOrganizationSecurityPolicyRequest( + security_policy="security_policy_value", + ) + + # Make the request + response = client.remove_rule(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_OrganizationSecurityPolicies_RemoveRule_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_get_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_get_sync.py new file mode 100644 index 000000000000..f0721666cc23 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_get_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_PreviewFeatures_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.PreviewFeaturesClient() + + # Initialize request argument(s) + request = compute_v1.GetPreviewFeatureRequest( + preview_feature="preview_feature_value", + project="project_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_PreviewFeatures_Get_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_list_sync.py new file mode 100644 index 000000000000..0f29457c4723 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_list_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_PreviewFeatures_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.PreviewFeaturesClient() + + # Initialize request argument(s) + request = compute_v1.ListPreviewFeaturesRequest( + 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_PreviewFeatures_List_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_update_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_update_sync.py new file mode 100644 index 000000000000..d4d401aa62f8 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_preview_features_update_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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_PreviewFeatures_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.PreviewFeaturesClient() + + # Initialize request argument(s) + request = compute_v1.UpdatePreviewFeatureRequest( + preview_feature="preview_feature_value", + project="project_value", + ) + + # Make the request + response = client.update(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_PreviewFeatures_Update_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_reservation_sub_blocks_report_faulty_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_reservation_sub_blocks_report_faulty_sync.py new file mode 100644 index 000000000000..4d136632da7b --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_reservation_sub_blocks_report_faulty_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 ReportFaulty +# 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_ReservationSubBlocks_ReportFaulty_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_report_faulty(): + # Create a client + client = compute_v1.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1.ReportFaultyReservationSubBlockRequest( + parent_name="parent_name_value", + project="project_value", + reservation_sub_block="reservation_sub_block_value", + zone="zone_value", + ) + + # Make the request + response = client.report_faulty(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_ReservationSubBlocks_ReportFaulty_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 585220b555ad..cbb187bacb14 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 @@ -2943,6 +2943,90 @@ ], "title": "compute_v1_generated_backend_services_delete_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.BackendServicesClient", + "shortName": "BackendServicesClient" + }, + "fullName": "google.cloud.compute_v1.BackendServicesClient.get_effective_security_policies", + "method": { + "fullName": "google.cloud.compute.v1.BackendServices.GetEffectiveSecurityPolicies", + "service": { + "fullName": "google.cloud.compute.v1.BackendServices", + "shortName": "BackendServices" + }, + "shortName": "GetEffectiveSecurityPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetEffectiveSecurityPoliciesBackendServiceRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "backend_service", + "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.GetEffectiveSecurityPoliciesBackendServiceResponse", + "shortName": "get_effective_security_policies" + }, + "description": "Sample for GetEffectiveSecurityPolicies", + "file": "compute_v1_generated_backend_services_get_effective_security_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_BackendServices_GetEffectiveSecurityPolicies_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_backend_services_get_effective_security_policies_sync.py" + }, { "canonical": true, "clientMethod": { @@ -35647,27 +35731,31 @@ "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.aggregated_list", + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.add_association", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.AggregatedList", + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.AddAssociation", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" }, - "shortName": "AggregatedList" + "shortName": "AddAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListPacketMirroringsRequest" + "type": "google.cloud.compute_v1.types.AddAssociationOrganizationSecurityPolicyRequest" }, { - "name": "project", + "name": "security_policy", "type": "str" }, + { + "name": "security_policy_association_resource", + "type": "google.cloud.compute_v1.types.SecurityPolicyAssociation" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35681,22 +35769,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.packet_mirrorings.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "add_association" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_packet_mirrorings_aggregated_list_sync.py", + "description": "Sample for AddAssociation", + "file": "compute_v1_generated_organization_security_policies_add_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_AggregatedList_sync", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_AddAssociation_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -35716,45 +35804,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_aggregated_list_sync.py" + "title": "compute_v1_generated_organization_security_policies_add_association_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.delete", + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.add_rule", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.Delete", + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.AddRule", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" }, - "shortName": "Delete" + "shortName": "AddRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeletePacketMirroringRequest" - }, - { - "name": "project", - "type": "str" + "type": "google.cloud.compute_v1.types.AddRuleOrganizationSecurityPolicyRequest" }, { - "name": "region", + "name": "security_policy", "type": "str" }, { - "name": "packet_mirroring", - "type": "str" + "name": "security_policy_rule_resource", + "type": "google.cloud.compute_v1.types.SecurityPolicyRule" }, { "name": "retry", @@ -35770,21 +35854,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "add_rule" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_packet_mirrorings_delete_sync.py", + "description": "Sample for AddRule", + "file": "compute_v1_generated_organization_security_policies_add_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_Delete_sync", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_AddRule_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -35794,54 +35878,126 @@ "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_packet_mirrorings_delete_sync.py" + "title": "compute_v1_generated_organization_security_policies_add_rule_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.get", + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.copy_rules", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.Get", + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.CopyRules", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" }, - "shortName": "Get" + "shortName": "CopyRules" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetPacketMirroringRequest" + "type": "google.cloud.compute_v1.types.CopyRulesOrganizationSecurityPolicyRequest" }, { - "name": "project", + "name": "security_policy", "type": "str" }, { - "name": "region", - "type": "str" + "name": "retry", + "type": "google.api_core.retry.Retry" }, { - "name": "packet_mirroring", + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "copy_rules" + }, + "description": "Sample for CopyRules", + "file": "compute_v1_generated_organization_security_policies_copy_rules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_CopyRules_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_organization_security_policies_copy_rules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.delete", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.Delete", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.DeleteOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", "type": "str" }, { @@ -35857,22 +36013,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.PacketMirroring", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for Get", - "file": "compute_v1_generated_packet_mirrorings_get_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_organization_security_policies_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_Get_sync", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_Delete_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -35882,55 +36038,127 @@ "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_packet_mirrorings_get_sync.py" + "title": "compute_v1_generated_organization_security_policies_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.insert", + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.get_association", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.Insert", + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.GetAssociation", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" }, - "shortName": "Insert" + "shortName": "GetAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertPacketMirroringRequest" + "type": "google.cloud.compute_v1.types.GetAssociationOrganizationSecurityPolicyRequest" }, { - "name": "project", + "name": "security_policy", "type": "str" }, { - "name": "region", - "type": "str" + "name": "retry", + "type": "google.api_core.retry.Retry" }, { - "name": "packet_mirroring_resource", - "type": "google.cloud.compute_v1.types.PacketMirroring" + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.SecurityPolicyAssociation", + "shortName": "get_association" + }, + "description": "Sample for GetAssociation", + "file": "compute_v1_generated_organization_security_policies_get_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_GetAssociation_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_organization_security_policies_get_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.get_rule", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.GetRule", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "GetRule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetRuleOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "type": "str" }, { "name": "retry", @@ -35945,22 +36173,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.types.SecurityPolicyRule", + "shortName": "get_rule" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_packet_mirrorings_insert_sync.py", + "description": "Sample for GetRule", + "file": "compute_v1_generated_organization_security_policies_get_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_Insert_sync", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_GetRule_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -35970,50 +36198,46 @@ "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_packet_mirrorings_insert_sync.py" + "title": "compute_v1_generated_organization_security_policies_get_rule_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.list", + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.get", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.List", + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.Get", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" }, - "shortName": "List" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListPacketMirroringsRequest" - }, - { - "name": "project", - "type": "str" + "type": "google.cloud.compute_v1.types.GetOrganizationSecurityPolicyRequest" }, { - "name": "region", + "name": "security_policy", "type": "str" }, { @@ -36029,22 +36253,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.services.packet_mirrorings.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.SecurityPolicy", + "shortName": "get" }, - "description": "Sample for List", - "file": "compute_v1_generated_packet_mirrorings_list_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_organization_security_policies_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_List_sync", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_Get_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -36054,59 +36278,123 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_list_sync.py" + "title": "compute_v1_generated_organization_security_policies_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.patch", + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.Patch", + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.Insert", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" }, - "shortName": "Patch" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchPacketMirroringRequest" + "type": "google.cloud.compute_v1.types.InsertOrganizationSecurityPolicyRequest" }, { - "name": "project", - "type": "str" + "name": "security_policy_resource", + "type": "google.cloud.compute_v1.types.SecurityPolicy" }, { - "name": "region", - "type": "str" + "name": "retry", + "type": "google.api_core.retry.Retry" }, { - "name": "packet_mirroring", - "type": "str" + "name": "timeout", + "type": "float" }, { - "name": "packet_mirroring_resource", - "type": "google.cloud.compute_v1.types.PacketMirroring" + "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_organization_security_policies_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_Insert_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_organization_security_policies_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.list_associations", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.ListAssociations", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "ListAssociations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListAssociationsOrganizationSecurityPolicyRequest" }, { "name": "retry", @@ -36121,14 +36409,1186 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.types.OrganizationSecurityPoliciesListAssociationsResponse", + "shortName": "list_associations" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_packet_mirrorings_patch_sync.py", + "description": "Sample for ListAssociations", + "file": "compute_v1_generated_organization_security_policies_list_associations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_Patch_sync", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_ListAssociations_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_organization_security_policies_list_associations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.list_preconfigured_expression_sets", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.ListPreconfiguredExpressionSets", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "ListPreconfiguredExpressionSets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest" + }, + { + "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.SecurityPoliciesListPreconfiguredExpressionSetsResponse", + "shortName": "list_preconfigured_expression_sets" + }, + "description": "Sample for ListPreconfiguredExpressionSets", + "file": "compute_v1_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_ListPreconfiguredExpressionSets_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.list", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.List", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListOrganizationSecurityPoliciesRequest" + }, + { + "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.organization_security_policies.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1_generated_organization_security_policies_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_List_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_organization_security_policies_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.move", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.Move", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "Move" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.MoveOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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": "move" + }, + "description": "Sample for Move", + "file": "compute_v1_generated_organization_security_policies_move_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_Move_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_organization_security_policies_move_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.patch_rule", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.PatchRule", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "PatchRule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.PatchRuleOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "type": "str" + }, + { + "name": "security_policy_rule_resource", + "type": "google.cloud.compute_v1.types.SecurityPolicyRule" + }, + { + "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_rule" + }, + "description": "Sample for PatchRule", + "file": "compute_v1_generated_organization_security_policies_patch_rule_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_PatchRule_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_organization_security_policies_patch_rule_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.patch", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.Patch", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "Patch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.PatchOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "type": "str" + }, + { + "name": "security_policy_resource", + "type": "google.cloud.compute_v1.types.SecurityPolicy" + }, + { + "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_organization_security_policies_patch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_Patch_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_organization_security_policies_patch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.remove_association", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.RemoveAssociation", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "RemoveAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.RemoveAssociationOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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": "remove_association" + }, + "description": "Sample for RemoveAssociation", + "file": "compute_v1_generated_organization_security_policies_remove_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_RemoveAssociation_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_organization_security_policies_remove_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.OrganizationSecurityPoliciesClient.remove_rule", + "method": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies.RemoveRule", + "service": { + "fullName": "google.cloud.compute.v1.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "RemoveRule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.RemoveRuleOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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": "remove_rule" + }, + "description": "Sample for RemoveRule", + "file": "compute_v1_generated_organization_security_policies_remove_rule_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_OrganizationSecurityPolicies_RemoveRule_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_organization_security_policies_remove_rule_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.aggregated_list", + "method": { + "fullName": "google.cloud.compute.v1.PacketMirrorings.AggregatedList", + "service": { + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "AggregatedList" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.AggregatedListPacketMirroringsRequest" + }, + { + "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.packet_mirrorings.pagers.AggregatedListPager", + "shortName": "aggregated_list" + }, + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_packet_mirrorings_aggregated_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PacketMirrorings_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_packet_mirrorings_aggregated_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.delete", + "method": { + "fullName": "google.cloud.compute.v1.PacketMirrorings.Delete", + "service": { + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.DeletePacketMirroringRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "packet_mirroring", + "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_packet_mirrorings_delete_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PacketMirrorings_Delete_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_packet_mirrorings_delete_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.get", + "method": { + "fullName": "google.cloud.compute.v1.PacketMirrorings.Get", + "service": { + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetPacketMirroringRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "packet_mirroring", + "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.PacketMirroring", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1_generated_packet_mirrorings_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PacketMirrorings_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_packet_mirrorings_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.insert", + "method": { + "fullName": "google.cloud.compute.v1.PacketMirrorings.Insert", + "service": { + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.InsertPacketMirroringRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "packet_mirroring_resource", + "type": "google.cloud.compute_v1.types.PacketMirroring" + }, + { + "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_packet_mirrorings_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PacketMirrorings_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_packet_mirrorings_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.list", + "method": { + "fullName": "google.cloud.compute.v1.PacketMirrorings.List", + "service": { + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListPacketMirroringsRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "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.packet_mirrorings.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1_generated_packet_mirrorings_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PacketMirrorings_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_packet_mirrorings_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.patch", + "method": { + "fullName": "google.cloud.compute.v1.PacketMirrorings.Patch", + "service": { + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "Patch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.PatchPacketMirroringRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "packet_mirroring", + "type": "str" + }, + { + "name": "packet_mirroring_resource", + "type": "google.cloud.compute_v1.types.PacketMirroring" + }, + { + "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_packet_mirrorings_patch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PacketMirrorings_Patch_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_packet_mirrorings_patch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.compute.v1.PacketMirrorings.TestIamPermissions", + "service": { + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.TestIamPermissionsPacketMirroringRequest" + }, + { + "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" + }, + { + "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_packet_mirrorings_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PacketMirrorings_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -36161,44 +37621,116 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_patch_sync.py" + "title": "compute_v1_generated_packet_mirrorings_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.PreviewFeaturesClient", + "shortName": "PreviewFeaturesClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.PreviewFeaturesClient.get", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.TestIamPermissions", + "fullName": "google.cloud.compute.v1.PreviewFeatures.Get", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.PreviewFeatures", + "shortName": "PreviewFeatures" }, - "shortName": "TestIamPermissions" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsPacketMirroringRequest" + "type": "google.cloud.compute_v1.types.GetPreviewFeatureRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "preview_feature", "type": "str" }, { - "name": "resource", - "type": "str" + "name": "retry", + "type": "google.api_core.retry.Retry" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1.types.PreviewFeature", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1_generated_preview_features_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PreviewFeatures_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_preview_features_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PreviewFeaturesClient", + "shortName": "PreviewFeaturesClient" + }, + "fullName": "google.cloud.compute_v1.PreviewFeaturesClient.list", + "method": { + "fullName": "google.cloud.compute.v1.PreviewFeatures.List", + "service": { + "fullName": "google.cloud.compute.v1.PreviewFeatures", + "shortName": "PreviewFeatures" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListPreviewFeaturesRequest" + }, + { + "name": "project", + "type": "str" }, { "name": "retry", @@ -36213,22 +37745,110 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.cloud.compute_v1.services.preview_features.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_packet_mirrorings_test_iam_permissions_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_preview_features_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_PreviewFeatures_List_sync", "segments": [ { - "end": 53, + "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_preview_features_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.PreviewFeaturesClient", + "shortName": "PreviewFeaturesClient" + }, + "fullName": "google.cloud.compute_v1.PreviewFeaturesClient.update", + "method": { + "fullName": "google.cloud.compute.v1.PreviewFeatures.Update", + "service": { + "fullName": "google.cloud.compute.v1.PreviewFeatures", + "shortName": "PreviewFeatures" + }, + "shortName": "Update" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.UpdatePreviewFeatureRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "preview_feature", + "type": "str" + }, + { + "name": "preview_feature_resource", + "type": "google.cloud.compute_v1.types.PreviewFeature" + }, + { + "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_preview_features_update_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PreviewFeatures_Update_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, "start": 27, "type": "SHORT" }, @@ -36238,22 +37858,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, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_test_iam_permissions_sync.py" + "title": "compute_v1_generated_preview_features_update_sync.py" }, { "canonical": true, @@ -54503,6 +56123,102 @@ ], "title": "compute_v1_generated_reservation_sub_blocks_perform_maintenance_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ReservationSubBlocksClient", + "shortName": "ReservationSubBlocksClient" + }, + "fullName": "google.cloud.compute_v1.ReservationSubBlocksClient.report_faulty", + "method": { + "fullName": "google.cloud.compute.v1.ReservationSubBlocks.ReportFaulty", + "service": { + "fullName": "google.cloud.compute.v1.ReservationSubBlocks", + "shortName": "ReservationSubBlocks" + }, + "shortName": "ReportFaulty" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ReportFaultyReservationSubBlockRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "parent_name", + "type": "str" + }, + { + "name": "reservation_sub_block", + "type": "str" + }, + { + "name": "reservation_sub_blocks_report_faulty_request_resource", + "type": "google.cloud.compute_v1.types.ReservationSubBlocksReportFaultyRequest" + }, + { + "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": "report_faulty" + }, + "description": "Sample for ReportFaulty", + "file": "compute_v1_generated_reservation_sub_blocks_report_faulty_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_ReservationSubBlocks_ReportFaulty_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_reservation_sub_blocks_report_faulty_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py b/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py index 8c5880c362fc..0729f1f8da35 100644 --- a/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py +++ b/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py @@ -61,6 +61,7 @@ class computeCallTransformer(cst.CSTTransformer): 'bulk_set_labels': ('bulk_zone_set_labels_request_resource', 'project', 'zone', 'request_id', 'resource', ), 'cancel': ('instance_group_manager', 'project', 'resize_request', 'zone', 'request_id', ), 'clone_rules': ('firewall_policy', 'request_id', 'source_firewall_policy', ), + 'copy_rules': ('security_policy', 'request_id', 'source_security_policy', ), 'create_instances': ('instance_group_manager', 'instance_group_managers_create_instances_request_resource', 'project', 'zone', 'request_id', ), 'create_members': ('interconnect_group', 'interconnect_groups_create_members_request_resource', 'project', ), 'create_snapshot': ('disk', 'project', 'snapshot_resource', 'zone', 'guest_flush', 'request_id', ), @@ -84,6 +85,7 @@ class computeCallTransformer(cst.CSTTransformer): 'get_association': ('firewall_policy', 'name', ), 'get_diagnostics': ('interconnect', 'project', ), 'get_effective_firewalls': ('instance', 'network_interface', 'project', 'zone', ), + 'get_effective_security_policies': ('backend_service', 'project', ), 'get_from_family': ('family', 'project', ), 'get_guest_attributes': ('instance', 'project', 'zone', 'query_path', 'variable_key', ), 'get_health': ('backend_service', 'project', 'resource_group_reference_resource', ), @@ -116,7 +118,7 @@ class computeCallTransformer(cst.CSTTransformer): 'list_nodes': ('node_group', 'project', 'zone', 'filter', 'max_results', 'order_by', 'page_token', 'return_partial_success', ), 'list_peering_routes': ('network', 'project', 'direction', 'filter', 'max_results', 'order_by', 'page_token', 'peering_name', 'region', 'return_partial_success', ), 'list_per_instance_configs': ('instance_group_manager', 'project', 'zone', 'filter', 'max_results', 'order_by', 'page_token', 'return_partial_success', ), - 'list_preconfigured_expression_sets': ('project', 'filter', 'max_results', 'order_by', 'page_token', 'return_partial_success', ), + 'list_preconfigured_expression_sets': ('filter', 'max_results', 'order_by', 'page_token', 'parent_id', 'return_partial_success', ), 'list_referrers': ('instance', 'project', 'zone', 'filter', 'max_results', 'order_by', 'page_token', 'return_partial_success', ), 'list_route_policies': ('project', 'region', 'router', 'filter', 'max_results', 'order_by', 'page_token', 'return_partial_success', ), 'list_usable': ('project', 'filter', 'max_results', 'order_by', 'page_token', 'return_partial_success', ), @@ -140,6 +142,7 @@ class computeCallTransformer(cst.CSTTransformer): 'remove_peering': ('network', 'networks_remove_peering_request_resource', 'project', 'request_id', ), 'remove_resource_policies': ('disk', 'disks_remove_resource_policies_request_resource', 'project', 'zone', 'request_id', ), 'remove_rule': ('firewall_policy', 'priority', 'request_id', ), + 'report_faulty': ('parent_name', 'project', 'reservation_sub_block', 'reservation_sub_blocks_report_faulty_request_resource', 'zone', 'request_id', ), 'report_host_as_faulty': ('instance', 'instances_report_host_as_faulty_request_resource', 'project', 'zone', 'request_id', ), 'request_remove_peering': ('network', 'networks_request_remove_peering_request_resource', 'project', 'request_id', ), 'reset': ('instance', 'project', 'zone', 'request_id', ), diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py index 84a8c54115ea..67149340798f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py @@ -2696,6 +2696,211 @@ def test_get_rest_flattened_error(transport: str = "rest"): ) +def test_get_effective_security_policies_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 = BackendServicesClient( + 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_effective_security_policies + 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_effective_security_policies + ] = mock_rpc + + request = {} + client.get_effective_security_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_effective_security_policies(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_effective_security_policies_rest_required_fields( + request_type=compute.GetEffectiveSecurityPoliciesBackendServiceRequest, +): + transport_class = transports.BackendServicesRestTransport + + request_init = {} + request_init["backend_service"] = "" + 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_effective_security_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["backendService"] = "backend_service_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_effective_security_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "backendService" in jsonified_request + assert jsonified_request["backendService"] == "backend_service_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = BackendServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.GetEffectiveSecurityPoliciesBackendServiceResponse() + # 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.GetEffectiveSecurityPoliciesBackendServiceResponse.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_effective_security_policies(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_effective_security_policies_rest_unset_required_fields(): + transport = transports.BackendServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_effective_security_policies._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "backendService", + "project", + ) + ) + ) + + +def test_get_effective_security_policies_rest_flattened(): + client = BackendServicesClient( + 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.GetEffectiveSecurityPoliciesBackendServiceResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "backend_service": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + backend_service="backend_service_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.GetEffectiveSecurityPoliciesBackendServiceResponse.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_effective_security_policies(**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/backendServices/{backend_service}/getEffectiveSecurityPolicies" + % client.transport._host, + args[1], + ) + + +def test_get_effective_security_policies_rest_flattened_error(transport: str = "rest"): + client = BackendServicesClient( + 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_effective_security_policies( + compute.GetEffectiveSecurityPoliciesBackendServiceRequest(), + project="project_value", + backend_service="backend_service_value", + ) + + def test_get_health_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7062,6 +7267,143 @@ def test_get_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_get_effective_security_policies_rest_bad_request( + request_type=compute.GetEffectiveSecurityPoliciesBackendServiceRequest, +): + client = BackendServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "backend_service": "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_effective_security_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetEffectiveSecurityPoliciesBackendServiceRequest, + dict, + ], +) +def test_get_effective_security_policies_rest_call_success(request_type): + client = BackendServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "backend_service": "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.GetEffectiveSecurityPoliciesBackendServiceResponse() + + # 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.GetEffectiveSecurityPoliciesBackendServiceResponse.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_effective_security_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, compute.GetEffectiveSecurityPoliciesBackendServiceResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_effective_security_policies_rest_interceptors(null_interceptor): + transport = transports.BackendServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BackendServicesRestInterceptor(), + ) + client = BackendServicesClient(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.BackendServicesRestInterceptor, + "post_get_effective_security_policies", + ) as post, mock.patch.object( + transports.BackendServicesRestInterceptor, + "post_get_effective_security_policies_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BackendServicesRestInterceptor, "pre_get_effective_security_policies" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetEffectiveSecurityPoliciesBackendServiceRequest.pb( + compute.GetEffectiveSecurityPoliciesBackendServiceRequest() + ) + 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.GetEffectiveSecurityPoliciesBackendServiceResponse.to_json( + compute.GetEffectiveSecurityPoliciesBackendServiceResponse() + ) + ) + req.return_value.content = return_value + + request = compute.GetEffectiveSecurityPoliciesBackendServiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.GetEffectiveSecurityPoliciesBackendServiceResponse() + post_with_metadata.return_value = ( + compute.GetEffectiveSecurityPoliciesBackendServiceResponse(), + metadata, + ) + + client.get_effective_security_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_get_health_rest_bad_request( request_type=compute.GetHealthBackendServiceRequest, ): @@ -10022,6 +10364,28 @@ 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_effective_security_policies_empty_call_rest(): + client = BackendServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_security_policies), "__call__" + ) as call: + client.get_effective_security_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetEffectiveSecurityPoliciesBackendServiceRequest() + + 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_health_empty_call_rest(): @@ -10275,6 +10639,7 @@ def test_backend_services_base_transport(): "delete", "delete_signed_url_key", "get", + "get_effective_security_policies", "get_health", "get_iam_policy", "insert", @@ -10438,6 +10803,9 @@ def test_backend_services_client_transport_session_collision(transport_name): session1 = client1.transport.get._session session2 = client2.transport.get._session assert session1 != session2 + session1 = client1.transport.get_effective_security_policies._session + session2 = client2.transport.get_effective_security_policies._session + assert session1 != session2 session1 = client1.transport.get_health._session session2 = client2.transport.get_health._session assert session1 != session2 diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disks.py index 9ff8c9cb776c..25b55490d78b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disks.py @@ -8844,6 +8844,7 @@ def test_create_snapshot_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "location_hint": "location_hint_value", "name": "name_value", + "params": {"resource_manager_tags": {}}, "satisfies_pzi": True, "satisfies_pzs": True, "self_link": "self_link_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_images.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_images.py index 60068e07da46..67a2002ea8fa 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_images.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_images.py @@ -5179,6 +5179,7 @@ def test_insert_rest_call_success(request_type): "license_codes": [1361, 1362], "licenses": ["licenses_value1", "licenses_value2"], "name": "name_value", + "params": {"resource_manager_tags": {}}, "raw_disk": { "container_type": "container_type_value", "sha1_checksum": "sha1_checksum_value", @@ -5593,6 +5594,7 @@ def test_patch_rest_call_success(request_type): "license_codes": [1361, 1362], "licenses": ["licenses_value1", "licenses_value2"], "name": "name_value", + "params": {"resource_manager_tags": {}}, "raw_disk": { "container_type": "container_type_value", "sha1_checksum": "sha1_checksum_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py index 641af194e71c..4ac1cdab27c3 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py @@ -3694,6 +3694,7 @@ def test_get_rest_call_success(request_type): satisfies_pzs=True, self_link="self_link_value", state="state_value", + subzone="subzone_value", ) # Wrap the value into a proper Response obj @@ -3738,6 +3739,7 @@ def test_get_rest_call_success(request_type): assert response.satisfies_pzs is True assert response.self_link == "self_link_value" assert response.state == "state_value" + assert response.subzone == "subzone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -4178,6 +4180,7 @@ def test_insert_rest_call_success(request_type): "satisfies_pzs": True, "self_link": "self_link_value", "state": "state_value", + "subzone": "subzone_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 @@ -4626,6 +4629,7 @@ def test_patch_rest_call_success(request_type): "satisfies_pzs": True, "self_link": "self_link_value", "state": "state_value", + "subzone": "subzone_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 diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_organization_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_organization_security_policies.py new file mode 100644 index 000000000000..2cdbbc9512a9 --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_organization_security_policies.py @@ -0,0 +1,10030 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +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 + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation # type: ignore +from google.api_core import retry as retries +import google.auth +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.organization_security_policies import ( + OrganizationSecurityPoliciesClient, + 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" + + assert OrganizationSecurityPoliciesClient._get_default_mtls_endpoint(None) is None + assert ( + OrganizationSecurityPoliciesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + OrganizationSecurityPoliciesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + OrganizationSecurityPoliciesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OrganizationSecurityPoliciesClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + OrganizationSecurityPoliciesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert OrganizationSecurityPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert OrganizationSecurityPoliciesClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert OrganizationSecurityPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + OrganizationSecurityPoliciesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert OrganizationSecurityPoliciesClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert OrganizationSecurityPoliciesClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert OrganizationSecurityPoliciesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + OrganizationSecurityPoliciesClient._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 OrganizationSecurityPoliciesClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ( + OrganizationSecurityPoliciesClient._get_client_cert_source(None, False) is None + ) + assert ( + OrganizationSecurityPoliciesClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + OrganizationSecurityPoliciesClient._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 ( + OrganizationSecurityPoliciesClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + OrganizationSecurityPoliciesClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + OrganizationSecurityPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationSecurityPoliciesClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = OrganizationSecurityPoliciesClient._DEFAULT_UNIVERSE + default_endpoint = ( + OrganizationSecurityPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + OrganizationSecurityPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + assert ( + OrganizationSecurityPoliciesClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + OrganizationSecurityPoliciesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == OrganizationSecurityPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationSecurityPoliciesClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + OrganizationSecurityPoliciesClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == OrganizationSecurityPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationSecurityPoliciesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == OrganizationSecurityPoliciesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationSecurityPoliciesClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + OrganizationSecurityPoliciesClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + OrganizationSecurityPoliciesClient._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 ( + OrganizationSecurityPoliciesClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + OrganizationSecurityPoliciesClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + OrganizationSecurityPoliciesClient._get_universe_domain(None, None) + == OrganizationSecurityPoliciesClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + OrganizationSecurityPoliciesClient._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 = OrganizationSecurityPoliciesClient(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 = OrganizationSecurityPoliciesClient(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", + [ + (OrganizationSecurityPoliciesClient, "rest"), + ], +) +def test_organization_security_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.OrganizationSecurityPoliciesRestTransport, "rest"), + ], +) +def test_organization_security_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", + [ + (OrganizationSecurityPoliciesClient, "rest"), + ], +) +def test_organization_security_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_organization_security_policies_client_get_transport_class(): + transport = OrganizationSecurityPoliciesClient.get_transport_class() + available_transports = [ + transports.OrganizationSecurityPoliciesRestTransport, + ] + assert transport in available_transports + + transport = OrganizationSecurityPoliciesClient.get_transport_class("rest") + assert transport == transports.OrganizationSecurityPoliciesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OrganizationSecurityPoliciesClient, + transports.OrganizationSecurityPoliciesRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + OrganizationSecurityPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationSecurityPoliciesClient), +) +def test_organization_security_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( + OrganizationSecurityPoliciesClient, "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( + OrganizationSecurityPoliciesClient, "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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # 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", + [ + ( + OrganizationSecurityPoliciesClient, + transports.OrganizationSecurityPoliciesRestTransport, + "rest", + "true", + ), + ( + OrganizationSecurityPoliciesClient, + transports.OrganizationSecurityPoliciesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + OrganizationSecurityPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationSecurityPoliciesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_organization_security_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", [OrganizationSecurityPoliciesClient]) +@mock.patch.object( + OrganizationSecurityPoliciesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OrganizationSecurityPoliciesClient), +) +def test_organization_security_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_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`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [OrganizationSecurityPoliciesClient]) +@mock.patch.object( + OrganizationSecurityPoliciesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationSecurityPoliciesClient), +) +def test_organization_security_policies_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = OrganizationSecurityPoliciesClient._DEFAULT_UNIVERSE + default_endpoint = ( + OrganizationSecurityPoliciesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + OrganizationSecurityPoliciesClient._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", + [ + ( + OrganizationSecurityPoliciesClient, + transports.OrganizationSecurityPoliciesRestTransport, + "rest", + ), + ], +) +def test_organization_security_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", + [ + ( + OrganizationSecurityPoliciesClient, + transports.OrganizationSecurityPoliciesRestTransport, + "rest", + None, + ), + ], +) +def test_organization_security_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_add_association_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 = OrganizationSecurityPoliciesClient( + 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.add_association 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.add_association] = mock_rpc + + request = {} + client.add_association(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.add_association(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_add_association_rest_required_fields( + request_type=compute.AddAssociationOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).add_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "replace_existing_association", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.add_association(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_association_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "replaceExistingAssociation", + "requestId", + ) + ) + & set( + ( + "securityPolicy", + "securityPolicyAssociationResource", + ) + ) + ) + + +def test_add_association_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_policy_value", + security_policy_association_resource=compute.SecurityPolicyAssociation( + attachment_id="attachment_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.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.add_association(**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/locations/global/securityPolicies/{security_policy}/addAssociation" + % client.transport._host, + args[1], + ) + + +def test_add_association_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.add_association( + compute.AddAssociationOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + security_policy_association_resource=compute.SecurityPolicyAssociation( + attachment_id="attachment_id_value" + ), + ) + + +def test_add_association_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 = OrganizationSecurityPoliciesClient( + 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.add_association 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.add_association] = mock_rpc + + request = {} + client.add_association_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.add_association_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_add_association_unary_rest_required_fields( + request_type=compute.AddAssociationOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).add_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "replace_existing_association", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.add_association_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_association_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "replaceExistingAssociation", + "requestId", + ) + ) + & set( + ( + "securityPolicy", + "securityPolicyAssociationResource", + ) + ) + ) + + +def test_add_association_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_policy_value", + security_policy_association_resource=compute.SecurityPolicyAssociation( + attachment_id="attachment_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.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.add_association_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/locations/global/securityPolicies/{security_policy}/addAssociation" + % client.transport._host, + args[1], + ) + + +def test_add_association_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.add_association_unary( + compute.AddAssociationOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + security_policy_association_resource=compute.SecurityPolicyAssociation( + attachment_id="attachment_id_value" + ), + ) + + +def test_add_rule_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 = OrganizationSecurityPoliciesClient( + 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.add_rule 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.add_rule] = mock_rpc + + request = {} + client.add_rule(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.add_rule(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_add_rule_rest_required_fields( + request_type=compute.AddRuleOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).add_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_rule._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 "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.add_rule(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_rule_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_rule._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "securityPolicy", + "securityPolicyRuleResource", + ) + ) + ) + + +def test_add_rule_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_policy_value", + security_policy_rule_resource=compute.SecurityPolicyRule( + action="action_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.add_rule(**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/locations/global/securityPolicies/{security_policy}/addRule" + % client.transport._host, + args[1], + ) + + +def test_add_rule_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.add_rule( + compute.AddRuleOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + security_policy_rule_resource=compute.SecurityPolicyRule( + action="action_value" + ), + ) + + +def test_add_rule_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 = OrganizationSecurityPoliciesClient( + 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.add_rule 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.add_rule] = mock_rpc + + request = {} + client.add_rule_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.add_rule_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_add_rule_unary_rest_required_fields( + request_type=compute.AddRuleOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).add_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_rule._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 "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.add_rule_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_rule_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_rule._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "securityPolicy", + "securityPolicyRuleResource", + ) + ) + ) + + +def test_add_rule_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_policy_value", + security_policy_rule_resource=compute.SecurityPolicyRule( + action="action_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.add_rule_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/locations/global/securityPolicies/{security_policy}/addRule" + % client.transport._host, + args[1], + ) + + +def test_add_rule_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.add_rule_unary( + compute.AddRuleOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + security_policy_rule_resource=compute.SecurityPolicyRule( + action="action_value" + ), + ) + + +def test_copy_rules_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 = OrganizationSecurityPoliciesClient( + 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.copy_rules 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.copy_rules] = mock_rpc + + request = {} + client.copy_rules(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.copy_rules(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_copy_rules_rest_required_fields( + request_type=compute.CopyRulesOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).copy_rules._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).copy_rules._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", + "source_security_policy", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.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.copy_rules(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_copy_rules_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.copy_rules._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "sourceSecurityPolicy", + ) + ) + & set(("securityPolicy",)) + ) + + +def test_copy_rules_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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.copy_rules(**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/locations/global/securityPolicies/{security_policy}/copyRules" + % client.transport._host, + args[1], + ) + + +def test_copy_rules_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.copy_rules( + compute.CopyRulesOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_copy_rules_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 = OrganizationSecurityPoliciesClient( + 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.copy_rules 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.copy_rules] = mock_rpc + + request = {} + client.copy_rules_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.copy_rules_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_copy_rules_unary_rest_required_fields( + request_type=compute.CopyRulesOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).copy_rules._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).copy_rules._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", + "source_security_policy", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.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.copy_rules_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_copy_rules_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.copy_rules._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "sourceSecurityPolicy", + ) + ) + & set(("securityPolicy",)) + ) + + +def test_copy_rules_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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.copy_rules_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/locations/global/securityPolicies/{security_policy}/copyRules" + % client.transport._host, + args[1], + ) + + +def test_copy_rules_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.copy_rules_unary( + compute.CopyRulesOrganizationSecurityPolicyRequest(), + security_policy="security_policy_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 = OrganizationSecurityPoliciesClient( + 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.DeleteOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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["securityPolicy"] = "security_policy_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 "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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 expected_params == actual_params + + +def test_delete_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("securityPolicy",))) + + +def test_delete_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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/locations/global/securityPolicies/{security_policy}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.DeleteOrganizationSecurityPolicyRequest(), + security_policy="security_policy_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 = OrganizationSecurityPoliciesClient( + 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.DeleteOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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["securityPolicy"] = "security_policy_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 "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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 expected_params == actual_params + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("securityPolicy",))) + + +def test_delete_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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/locations/global/securityPolicies/{security_policy}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.DeleteOrganizationSecurityPolicyRequest(), + security_policy="security_policy_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 = OrganizationSecurityPoliciesClient( + 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.GetOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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["securityPolicy"] = "security_policy_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 "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.SecurityPolicy() + # 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.SecurityPolicy.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 expected_params == actual_params + + +def test_get_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("securityPolicy",))) + + +def test_get_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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.SecurityPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.SecurityPolicy.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/locations/global/securityPolicies/{security_policy}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.GetOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_get_association_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 = OrganizationSecurityPoliciesClient( + 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_association 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_association] = mock_rpc + + request = {} + client.get_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_association(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_association_rest_required_fields( + request_type=compute.GetAssociationOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("name",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.SecurityPolicyAssociation() + # 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.SecurityPolicyAssociation.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_association(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_association_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_association._get_unset_required_fields({}) + assert set(unset_fields) == (set(("name",)) & set(("securityPolicy",))) + + +def test_get_association_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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.SecurityPolicyAssociation() + + # get arguments that satisfy an http rule for this method + sample_request = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.SecurityPolicyAssociation.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_association(**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/locations/global/securityPolicies/{security_policy}/getAssociation" + % client.transport._host, + args[1], + ) + + +def test_get_association_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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_association( + compute.GetAssociationOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_get_rule_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 = OrganizationSecurityPoliciesClient( + 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_rule 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_rule] = mock_rpc + + request = {} + client.get_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_rule(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_rule_rest_required_fields( + request_type=compute.GetRuleOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("priority",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.SecurityPolicyRule() + # 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.SecurityPolicyRule.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_rule(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_rule_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(("priority",)) & set(("securityPolicy",))) + + +def test_get_rule_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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.SecurityPolicyRule() + + # get arguments that satisfy an http rule for this method + sample_request = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.SecurityPolicyRule.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_rule(**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/locations/global/securityPolicies/{security_policy}/getRule" + % client.transport._host, + args[1], + ) + + +def test_get_rule_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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_rule( + compute.GetRuleOrganizationSecurityPolicyRequest(), + security_policy="security_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 = OrganizationSecurityPoliciesClient( + 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.InsertOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + 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 + + 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( + ( + "parent_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = OrganizationSecurityPoliciesClient( + 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 expected_params == actual_params + + +def test_insert_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "parentId", + "requestId", + ) + ) + & set(("securityPolicyResource",)) + ) + + +def test_insert_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {} + + # get truthy value for each flattened field + mock_args = dict( + security_policy_resource=compute.SecurityPolicy( + adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( + layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( + enable=True + ) + ) + ), + ) + 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/locations/global/securityPolicies" % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.InsertOrganizationSecurityPolicyRequest(), + security_policy_resource=compute.SecurityPolicy( + adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( + layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( + enable=True + ) + ) + ), + ) + + +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 = OrganizationSecurityPoliciesClient( + 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.InsertOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + 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 + + 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( + ( + "parent_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = OrganizationSecurityPoliciesClient( + 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 expected_params == actual_params + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "parentId", + "requestId", + ) + ) + & set(("securityPolicyResource",)) + ) + + +def test_insert_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {} + + # get truthy value for each flattened field + mock_args = dict( + security_policy_resource=compute.SecurityPolicy( + adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( + layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( + enable=True + ) + ) + ), + ) + 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/locations/global/securityPolicies" % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.InsertOrganizationSecurityPolicyRequest(), + security_policy_resource=compute.SecurityPolicy( + adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( + layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( + enable=True + ) + ) + ), + ) + + +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 = OrganizationSecurityPoliciesClient( + 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_pager(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.SecurityPolicyList( + items=[ + compute.SecurityPolicy(), + compute.SecurityPolicy(), + compute.SecurityPolicy(), + ], + next_page_token="abc", + ), + compute.SecurityPolicyList( + items=[], + next_page_token="def", + ), + compute.SecurityPolicyList( + items=[ + compute.SecurityPolicy(), + ], + next_page_token="ghi", + ), + compute.SecurityPolicyList( + items=[ + compute.SecurityPolicy(), + compute.SecurityPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.SecurityPolicyList.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 = {} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.SecurityPolicy) 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_list_associations_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 = OrganizationSecurityPoliciesClient( + 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_associations 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_associations + ] = mock_rpc + + request = {} + client.list_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_associations(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_preconfigured_expression_sets_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 = OrganizationSecurityPoliciesClient( + 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_preconfigured_expression_sets + 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_preconfigured_expression_sets + ] = mock_rpc + + request = {} + client.list_preconfigured_expression_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_preconfigured_expression_sets(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_move_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 = OrganizationSecurityPoliciesClient( + 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.move 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.move] = mock_rpc + + request = {} + client.move(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.move(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_move_rest_required_fields( + request_type=compute.MoveOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).move._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).move._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "parent_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.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.move(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_move_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.move._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "parentId", + "requestId", + ) + ) + & set(("securityPolicy",)) + ) + + +def test_move_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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.move(**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/locations/global/securityPolicies/{security_policy}/move" + % client.transport._host, + args[1], + ) + + +def test_move_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.move( + compute.MoveOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_move_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 = OrganizationSecurityPoliciesClient( + 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.move 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.move] = mock_rpc + + request = {} + client.move_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.move_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_move_unary_rest_required_fields( + request_type=compute.MoveOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).move._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).move._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "parent_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.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.move_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_move_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.move._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "parentId", + "requestId", + ) + ) + & set(("securityPolicy",)) + ) + + +def test_move_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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.move_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/locations/global/securityPolicies/{security_policy}/move" + % client.transport._host, + args[1], + ) + + +def test_move_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.move_unary( + compute.MoveOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_patch_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 = OrganizationSecurityPoliciesClient( + 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.patch 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.patch] = mock_rpc + + request = {} + client.patch(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.patch(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_patch_rest_required_fields( + request_type=compute.PatchOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).patch._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch._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 "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.patch(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "securityPolicy", + "securityPolicyResource", + ) + ) + ) + + +def test_patch_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_policy_value", + security_policy_resource=compute.SecurityPolicy( + adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( + layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( + enable=True + ) + ) + ), + ) + 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.patch(**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/locations/global/securityPolicies/{security_policy}" + % client.transport._host, + args[1], + ) + + +def test_patch_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.patch( + compute.PatchOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + security_policy_resource=compute.SecurityPolicy( + adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( + layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( + enable=True + ) + ) + ), + ) + + +def test_patch_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 = OrganizationSecurityPoliciesClient( + 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.patch 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.patch] = mock_rpc + + request = {} + client.patch_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.patch_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_patch_unary_rest_required_fields( + request_type=compute.PatchOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).patch._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch._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 "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.patch_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "securityPolicy", + "securityPolicyResource", + ) + ) + ) + + +def test_patch_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_policy_value", + security_policy_resource=compute.SecurityPolicy( + adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( + layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( + enable=True + ) + ) + ), + ) + 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.patch_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/locations/global/securityPolicies/{security_policy}" + % client.transport._host, + args[1], + ) + + +def test_patch_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.patch_unary( + compute.PatchOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + security_policy_resource=compute.SecurityPolicy( + adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( + layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( + enable=True + ) + ) + ), + ) + + +def test_patch_rule_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 = OrganizationSecurityPoliciesClient( + 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.patch_rule 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.patch_rule] = mock_rpc + + request = {} + client.patch_rule(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.patch_rule(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_patch_rule_rest_required_fields( + request_type=compute.PatchRuleOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).patch_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "priority", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.patch_rule(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_rule_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch_rule._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "priority", + "requestId", + ) + ) + & set( + ( + "securityPolicy", + "securityPolicyRuleResource", + ) + ) + ) + + +def test_patch_rule_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_policy_value", + security_policy_rule_resource=compute.SecurityPolicyRule( + action="action_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.patch_rule(**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/locations/global/securityPolicies/{security_policy}/patchRule" + % client.transport._host, + args[1], + ) + + +def test_patch_rule_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.patch_rule( + compute.PatchRuleOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + security_policy_rule_resource=compute.SecurityPolicyRule( + action="action_value" + ), + ) + + +def test_patch_rule_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 = OrganizationSecurityPoliciesClient( + 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.patch_rule 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.patch_rule] = mock_rpc + + request = {} + client.patch_rule_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.patch_rule_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_patch_rule_unary_rest_required_fields( + request_type=compute.PatchRuleOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).patch_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "priority", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.patch_rule_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_patch_rule_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch_rule._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "priority", + "requestId", + ) + ) + & set( + ( + "securityPolicy", + "securityPolicyRuleResource", + ) + ) + ) + + +def test_patch_rule_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_policy_value", + security_policy_rule_resource=compute.SecurityPolicyRule( + action="action_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.patch_rule_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/locations/global/securityPolicies/{security_policy}/patchRule" + % client.transport._host, + args[1], + ) + + +def test_patch_rule_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.patch_rule_unary( + compute.PatchRuleOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + security_policy_rule_resource=compute.SecurityPolicyRule( + action="action_value" + ), + ) + + +def test_remove_association_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 = OrganizationSecurityPoliciesClient( + 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.remove_association 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.remove_association + ] = mock_rpc + + request = {} + client.remove_association(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.remove_association(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_remove_association_rest_required_fields( + request_type=compute.RemoveAssociationOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).remove_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "name", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.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.remove_association(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_association_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "name", + "requestId", + ) + ) + & set(("securityPolicy",)) + ) + + +def test_remove_association_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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.remove_association(**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/locations/global/securityPolicies/{security_policy}/removeAssociation" + % client.transport._host, + args[1], + ) + + +def test_remove_association_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.remove_association( + compute.RemoveAssociationOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_remove_association_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 = OrganizationSecurityPoliciesClient( + 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.remove_association 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.remove_association + ] = mock_rpc + + request = {} + client.remove_association_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.remove_association_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_remove_association_unary_rest_required_fields( + request_type=compute.RemoveAssociationOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).remove_association._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "name", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.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.remove_association_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_association_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_association._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "name", + "requestId", + ) + ) + & set(("securityPolicy",)) + ) + + +def test_remove_association_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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.remove_association_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/locations/global/securityPolicies/{security_policy}/removeAssociation" + % client.transport._host, + args[1], + ) + + +def test_remove_association_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.remove_association_unary( + compute.RemoveAssociationOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_remove_rule_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 = OrganizationSecurityPoliciesClient( + 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.remove_rule 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.remove_rule] = mock_rpc + + request = {} + client.remove_rule(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.remove_rule(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_remove_rule_rest_required_fields( + request_type=compute.RemoveRuleOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).remove_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "priority", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.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.remove_rule(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_rule_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_rule._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "priority", + "requestId", + ) + ) + & set(("securityPolicy",)) + ) + + +def test_remove_rule_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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.remove_rule(**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/locations/global/securityPolicies/{security_policy}/removeRule" + % client.transport._host, + args[1], + ) + + +def test_remove_rule_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.remove_rule( + compute.RemoveRuleOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_remove_rule_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 = OrganizationSecurityPoliciesClient( + 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.remove_rule 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.remove_rule] = mock_rpc + + request = {} + client.remove_rule_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.remove_rule_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_remove_rule_unary_rest_required_fields( + request_type=compute.RemoveRuleOrganizationSecurityPolicyRequest, +): + transport_class = transports.OrganizationSecurityPoliciesRestTransport + + request_init = {} + request_init["security_policy"] = "" + 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() + ).remove_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["securityPolicy"] = "security_policy_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_rule._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "priority", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "securityPolicy" in jsonified_request + assert jsonified_request["securityPolicy"] == "security_policy_value" + + client = OrganizationSecurityPoliciesClient( + 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.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.remove_rule_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_rule_unary_rest_unset_required_fields(): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_rule._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "priority", + "requestId", + ) + ) + & set(("securityPolicy",)) + ) + + +def test_remove_rule_unary_rest_flattened(): + client = OrganizationSecurityPoliciesClient( + 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 = {"security_policy": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + security_policy="security_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.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.remove_rule_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/locations/global/securityPolicies/{security_policy}/removeRule" + % client.transport._host, + args[1], + ) + + +def test_remove_rule_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationSecurityPoliciesClient( + 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.remove_rule_unary( + compute.RemoveRuleOrganizationSecurityPolicyRequest(), + security_policy="security_policy_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationSecurityPoliciesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationSecurityPoliciesClient( + 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 = OrganizationSecurityPoliciesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationSecurityPoliciesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OrganizationSecurityPoliciesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationSecurityPoliciesRestTransport, + ], +) +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 = OrganizationSecurityPoliciesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_add_association_rest_bad_request( + request_type=compute.AddAssociationOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.add_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AddAssociationOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_add_association_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "sample1"} + request_init["security_policy_association_resource"] = { + "attachment_id": "attachment_id_value", + "display_name": "display_name_value", + "excluded_folders": ["excluded_folders_value1", "excluded_folders_value2"], + "excluded_projects": ["excluded_projects_value1", "excluded_projects_value2"], + "name": "name_value", + "security_policy_id": "security_policy_id_value", + "short_name": "short_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.AddAssociationOrganizationSecurityPolicyRequest.meta.fields[ + "security_policy_association_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[ + "security_policy_association_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["security_policy_association_resource"][field]) + ): + del request_init["security_policy_association_resource"][field][i][ + subfield + ] + else: + del request_init["security_policy_association_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.add_association(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_add_association_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_add_association" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_add_association_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_add_association" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AddAssociationOrganizationSecurityPolicyRequest.pb( + compute.AddAssociationOrganizationSecurityPolicyRequest() + ) + 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.AddAssociationOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.add_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_add_rule_rest_bad_request( + request_type=compute.AddRuleOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.add_rule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AddRuleOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_add_rule_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "sample1"} + request_init["security_policy_rule_resource"] = { + "action": "action_value", + "description": "description_value", + "header_action": { + "request_headers_to_adds": [ + { + "header_name": "header_name_value", + "header_value": "header_value_value", + } + ] + }, + "kind": "kind_value", + "match": { + "config": { + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"] + }, + "expr": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "expr_options": { + "recaptcha_options": { + "action_token_site_keys": [ + "action_token_site_keys_value1", + "action_token_site_keys_value2", + ], + "session_token_site_keys": [ + "session_token_site_keys_value1", + "session_token_site_keys_value2", + ], + } + }, + "versioned_expr": "versioned_expr_value", + }, + "network_match": { + "dest_ip_ranges": ["dest_ip_ranges_value1", "dest_ip_ranges_value2"], + "dest_ports": ["dest_ports_value1", "dest_ports_value2"], + "ip_protocols": ["ip_protocols_value1", "ip_protocols_value2"], + "src_asns": [861, 862], + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"], + "src_ports": ["src_ports_value1", "src_ports_value2"], + "src_region_codes": ["src_region_codes_value1", "src_region_codes_value2"], + "user_defined_fields": [ + {"name": "name_value", "values": ["values_value1", "values_value2"]} + ], + }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, + "preview": True, + "priority": 898, + "rate_limit_options": { + "ban_duration_sec": 1680, + "ban_threshold": {"count": 553, "interval_sec": 1279}, + "conform_action": "conform_action_value", + "enforce_on_key": "enforce_on_key_value", + "enforce_on_key_configs": [ + { + "enforce_on_key_name": "enforce_on_key_name_value", + "enforce_on_key_type": "enforce_on_key_type_value", + } + ], + "enforce_on_key_name": "enforce_on_key_name_value", + "exceed_action": "exceed_action_value", + "exceed_redirect_options": { + "target": "target_value", + "type_": "type__value", + }, + "rate_limit_threshold": {}, + }, + "redirect_options": {}, + } + # 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.AddRuleOrganizationSecurityPolicyRequest.meta.fields[ + "security_policy_rule_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[ + "security_policy_rule_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["security_policy_rule_resource"][field]) + ): + del request_init["security_policy_rule_resource"][field][i][ + subfield + ] + else: + del request_init["security_policy_rule_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.add_rule(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_add_rule_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_add_rule" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_add_rule_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_add_rule" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AddRuleOrganizationSecurityPolicyRequest.pb( + compute.AddRuleOrganizationSecurityPolicyRequest() + ) + 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.AddRuleOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.add_rule( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_copy_rules_rest_bad_request( + request_type=compute.CopyRulesOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.copy_rules(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CopyRulesOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_copy_rules_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.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.copy_rules(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_copy_rules_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_copy_rules" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_copy_rules_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_copy_rules" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CopyRulesOrganizationSecurityPolicyRequest.pb( + compute.CopyRulesOrganizationSecurityPolicyRequest() + ) + 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.CopyRulesOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.copy_rules( + 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.DeleteOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.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.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_delete_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteOrganizationSecurityPolicyRequest.pb( + compute.DeleteOrganizationSecurityPolicyRequest() + ) + 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.DeleteOrganizationSecurityPolicyRequest() + 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.GetOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.SecurityPolicy( + creation_timestamp="creation_timestamp_value", + description="description_value", + fingerprint="fingerprint_value", + id=205, + kind="kind_value", + label_fingerprint="label_fingerprint_value", + name="name_value", + region="region_value", + self_link="self_link_value", + short_name="short_name_value", + type_="type__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.SecurityPolicy.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.SecurityPolicy) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.fingerprint == "fingerprint_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.label_fingerprint == "label_fingerprint_value" + assert response.name == "name_value" + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.short_name == "short_name_value" + assert response.type_ == "type__value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetOrganizationSecurityPolicyRequest.pb( + compute.GetOrganizationSecurityPolicyRequest() + ) + 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.SecurityPolicy.to_json(compute.SecurityPolicy()) + req.return_value.content = return_value + + request = compute.GetOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.SecurityPolicy() + post_with_metadata.return_value = compute.SecurityPolicy(), 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_association_rest_bad_request( + request_type=compute.GetAssociationOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.get_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetAssociationOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_get_association_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.SecurityPolicyAssociation( + attachment_id="attachment_id_value", + display_name="display_name_value", + excluded_folders=["excluded_folders_value"], + excluded_projects=["excluded_projects_value"], + name="name_value", + security_policy_id="security_policy_id_value", + short_name="short_name_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.SecurityPolicyAssociation.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_association(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.SecurityPolicyAssociation) + assert response.attachment_id == "attachment_id_value" + assert response.display_name == "display_name_value" + assert response.excluded_folders == ["excluded_folders_value"] + assert response.excluded_projects == ["excluded_projects_value"] + assert response.name == "name_value" + assert response.security_policy_id == "security_policy_id_value" + assert response.short_name == "short_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_association_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_get_association" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_get_association_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_get_association" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetAssociationOrganizationSecurityPolicyRequest.pb( + compute.GetAssociationOrganizationSecurityPolicyRequest() + ) + 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.SecurityPolicyAssociation.to_json( + compute.SecurityPolicyAssociation() + ) + req.return_value.content = return_value + + request = compute.GetAssociationOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.SecurityPolicyAssociation() + post_with_metadata.return_value = compute.SecurityPolicyAssociation(), metadata + + client.get_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rule_rest_bad_request( + request_type=compute.GetRuleOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.get_rule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetRuleOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_get_rule_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.SecurityPolicyRule( + action="action_value", + description="description_value", + kind="kind_value", + preview=True, + priority=898, + ) + + # 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.SecurityPolicyRule.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_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.SecurityPolicyRule) + assert response.action == "action_value" + assert response.description == "description_value" + assert response.kind == "kind_value" + assert response.preview is True + assert response.priority == 898 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rule_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_get_rule" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_get_rule_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_get_rule" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRuleOrganizationSecurityPolicyRequest.pb( + compute.GetRuleOrganizationSecurityPolicyRequest() + ) + 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.SecurityPolicyRule.to_json(compute.SecurityPolicyRule()) + req.return_value.content = return_value + + request = compute.GetRuleOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.SecurityPolicyRule() + post_with_metadata.return_value = compute.SecurityPolicyRule(), metadata + + client.get_rule( + 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.InsertOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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.InsertOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_insert_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["security_policy_resource"] = { + "adaptive_protection_config": { + "layer7_ddos_defense_config": { + "enable": True, + "rule_visibility": "rule_visibility_value", + "threshold_configs": [ + { + "auto_deploy_confidence_threshold": 0.339, + "auto_deploy_expiration_sec": 2785, + "auto_deploy_impacted_baseline_threshold": 0.4121, + "auto_deploy_load_threshold": 0.2768, + "detection_absolute_qps": 0.23520000000000002, + "detection_load_threshold": 0.2538, + "detection_relative_to_baseline_qps": 0.36010000000000003, + "name": "name_value", + "traffic_granularity_configs": [ + { + "enable_each_unique_value": True, + "type_": "type__value", + "value": "value_value", + } + ], + } + ], + } + }, + "advanced_options_config": { + "json_custom_config": { + "content_types": ["content_types_value1", "content_types_value2"] + }, + "json_parsing": "json_parsing_value", + "log_level": "log_level_value", + "user_ip_request_headers": [ + "user_ip_request_headers_value1", + "user_ip_request_headers_value2", + ], + }, + "associations": [ + { + "attachment_id": "attachment_id_value", + "display_name": "display_name_value", + "excluded_folders": [ + "excluded_folders_value1", + "excluded_folders_value2", + ], + "excluded_projects": [ + "excluded_projects_value1", + "excluded_projects_value2", + ], + "name": "name_value", + "security_policy_id": "security_policy_id_value", + "short_name": "short_name_value", + } + ], + "creation_timestamp": "creation_timestamp_value", + "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, + "description": "description_value", + "fingerprint": "fingerprint_value", + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "name": "name_value", + "recaptcha_options_config": {"redirect_site_key": "redirect_site_key_value"}, + "region": "region_value", + "rules": [ + { + "action": "action_value", + "description": "description_value", + "header_action": { + "request_headers_to_adds": [ + { + "header_name": "header_name_value", + "header_value": "header_value_value", + } + ] + }, + "kind": "kind_value", + "match": { + "config": { + "src_ip_ranges": [ + "src_ip_ranges_value1", + "src_ip_ranges_value2", + ] + }, + "expr": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "expr_options": { + "recaptcha_options": { + "action_token_site_keys": [ + "action_token_site_keys_value1", + "action_token_site_keys_value2", + ], + "session_token_site_keys": [ + "session_token_site_keys_value1", + "session_token_site_keys_value2", + ], + } + }, + "versioned_expr": "versioned_expr_value", + }, + "network_match": { + "dest_ip_ranges": [ + "dest_ip_ranges_value1", + "dest_ip_ranges_value2", + ], + "dest_ports": ["dest_ports_value1", "dest_ports_value2"], + "ip_protocols": ["ip_protocols_value1", "ip_protocols_value2"], + "src_asns": [861, 862], + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"], + "src_ports": ["src_ports_value1", "src_ports_value2"], + "src_region_codes": [ + "src_region_codes_value1", + "src_region_codes_value2", + ], + "user_defined_fields": [ + { + "name": "name_value", + "values": ["values_value1", "values_value2"], + } + ], + }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, + "preview": True, + "priority": 898, + "rate_limit_options": { + "ban_duration_sec": 1680, + "ban_threshold": {"count": 553, "interval_sec": 1279}, + "conform_action": "conform_action_value", + "enforce_on_key": "enforce_on_key_value", + "enforce_on_key_configs": [ + { + "enforce_on_key_name": "enforce_on_key_name_value", + "enforce_on_key_type": "enforce_on_key_type_value", + } + ], + "enforce_on_key_name": "enforce_on_key_name_value", + "exceed_action": "exceed_action_value", + "exceed_redirect_options": { + "target": "target_value", + "type_": "type__value", + }, + "rate_limit_threshold": {}, + }, + "redirect_options": {}, + } + ], + "self_link": "self_link_value", + "short_name": "short_name_value", + "type_": "type__value", + "user_defined_fields": [ + { + "base": "base_value", + "mask": "mask_value", + "name": "name_value", + "offset": 647, + "size": 443, + } + ], + } + # 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.InsertOrganizationSecurityPolicyRequest.meta.fields[ + "security_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[ + "security_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["security_policy_resource"][field])): + del request_init["security_policy_resource"][field][i][subfield] + else: + del request_init["security_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.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_insert_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.InsertOrganizationSecurityPolicyRequest.pb( + compute.InsertOrganizationSecurityPolicyRequest() + ) + 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.InsertOrganizationSecurityPolicyRequest() + 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.ListOrganizationSecurityPoliciesRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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.ListOrganizationSecurityPoliciesRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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.SecurityPolicyList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_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.SecurityPolicyList.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.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_list_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListOrganizationSecurityPoliciesRequest.pb( + compute.ListOrganizationSecurityPoliciesRequest() + ) + 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.SecurityPolicyList.to_json(compute.SecurityPolicyList()) + req.return_value.content = return_value + + request = compute.ListOrganizationSecurityPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.SecurityPolicyList() + post_with_metadata.return_value = compute.SecurityPolicyList(), 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_list_associations_rest_bad_request( + request_type=compute.ListAssociationsOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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_associations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListAssociationsOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_list_associations_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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.OrganizationSecurityPoliciesListAssociationsResponse( + kind="kind_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.OrganizationSecurityPoliciesListAssociationsResponse.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_associations(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, compute.OrganizationSecurityPoliciesListAssociationsResponse + ) + assert response.kind == "kind_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_associations_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_list_associations" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_list_associations_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_list_associations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListAssociationsOrganizationSecurityPolicyRequest.pb( + compute.ListAssociationsOrganizationSecurityPolicyRequest() + ) + 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.OrganizationSecurityPoliciesListAssociationsResponse.to_json( + compute.OrganizationSecurityPoliciesListAssociationsResponse() + ) + ) + req.return_value.content = return_value + + request = compute.ListAssociationsOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + compute.OrganizationSecurityPoliciesListAssociationsResponse() + ) + post_with_metadata.return_value = ( + compute.OrganizationSecurityPoliciesListAssociationsResponse(), + metadata, + ) + + client.list_associations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_preconfigured_expression_sets_rest_bad_request( + request_type=compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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_preconfigured_expression_sets(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest, + dict, + ], +) +def test_list_preconfigured_expression_sets_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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.SecurityPoliciesListPreconfiguredExpressionSetsResponse() + + # 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.SecurityPoliciesListPreconfiguredExpressionSetsResponse.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_preconfigured_expression_sets(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_preconfigured_expression_sets_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, + "post_list_preconfigured_expression_sets", + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_list_preconfigured_expression_sets_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "pre_list_preconfigured_expression_sets", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest.pb( + compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest() + ) + 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.SecurityPoliciesListPreconfiguredExpressionSetsResponse.to_json( + compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse() + ) + ) + req.return_value.content = return_value + + request = ( + compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse() + ) + post_with_metadata.return_value = ( + compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse(), + metadata, + ) + + client.list_preconfigured_expression_sets( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_move_rest_bad_request( + request_type=compute.MoveOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.move(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.MoveOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_move_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.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.move(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_move_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_move" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_move_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_move" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.MoveOrganizationSecurityPolicyRequest.pb( + compute.MoveOrganizationSecurityPolicyRequest() + ) + 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.MoveOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.move( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_patch_rest_bad_request( + request_type=compute.PatchOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.patch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.PatchOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_patch_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "sample1"} + request_init["security_policy_resource"] = { + "adaptive_protection_config": { + "layer7_ddos_defense_config": { + "enable": True, + "rule_visibility": "rule_visibility_value", + "threshold_configs": [ + { + "auto_deploy_confidence_threshold": 0.339, + "auto_deploy_expiration_sec": 2785, + "auto_deploy_impacted_baseline_threshold": 0.4121, + "auto_deploy_load_threshold": 0.2768, + "detection_absolute_qps": 0.23520000000000002, + "detection_load_threshold": 0.2538, + "detection_relative_to_baseline_qps": 0.36010000000000003, + "name": "name_value", + "traffic_granularity_configs": [ + { + "enable_each_unique_value": True, + "type_": "type__value", + "value": "value_value", + } + ], + } + ], + } + }, + "advanced_options_config": { + "json_custom_config": { + "content_types": ["content_types_value1", "content_types_value2"] + }, + "json_parsing": "json_parsing_value", + "log_level": "log_level_value", + "user_ip_request_headers": [ + "user_ip_request_headers_value1", + "user_ip_request_headers_value2", + ], + }, + "associations": [ + { + "attachment_id": "attachment_id_value", + "display_name": "display_name_value", + "excluded_folders": [ + "excluded_folders_value1", + "excluded_folders_value2", + ], + "excluded_projects": [ + "excluded_projects_value1", + "excluded_projects_value2", + ], + "name": "name_value", + "security_policy_id": "security_policy_id_value", + "short_name": "short_name_value", + } + ], + "creation_timestamp": "creation_timestamp_value", + "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, + "description": "description_value", + "fingerprint": "fingerprint_value", + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "name": "name_value", + "recaptcha_options_config": {"redirect_site_key": "redirect_site_key_value"}, + "region": "region_value", + "rules": [ + { + "action": "action_value", + "description": "description_value", + "header_action": { + "request_headers_to_adds": [ + { + "header_name": "header_name_value", + "header_value": "header_value_value", + } + ] + }, + "kind": "kind_value", + "match": { + "config": { + "src_ip_ranges": [ + "src_ip_ranges_value1", + "src_ip_ranges_value2", + ] + }, + "expr": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "expr_options": { + "recaptcha_options": { + "action_token_site_keys": [ + "action_token_site_keys_value1", + "action_token_site_keys_value2", + ], + "session_token_site_keys": [ + "session_token_site_keys_value1", + "session_token_site_keys_value2", + ], + } + }, + "versioned_expr": "versioned_expr_value", + }, + "network_match": { + "dest_ip_ranges": [ + "dest_ip_ranges_value1", + "dest_ip_ranges_value2", + ], + "dest_ports": ["dest_ports_value1", "dest_ports_value2"], + "ip_protocols": ["ip_protocols_value1", "ip_protocols_value2"], + "src_asns": [861, 862], + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"], + "src_ports": ["src_ports_value1", "src_ports_value2"], + "src_region_codes": [ + "src_region_codes_value1", + "src_region_codes_value2", + ], + "user_defined_fields": [ + { + "name": "name_value", + "values": ["values_value1", "values_value2"], + } + ], + }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, + "preview": True, + "priority": 898, + "rate_limit_options": { + "ban_duration_sec": 1680, + "ban_threshold": {"count": 553, "interval_sec": 1279}, + "conform_action": "conform_action_value", + "enforce_on_key": "enforce_on_key_value", + "enforce_on_key_configs": [ + { + "enforce_on_key_name": "enforce_on_key_name_value", + "enforce_on_key_type": "enforce_on_key_type_value", + } + ], + "enforce_on_key_name": "enforce_on_key_name_value", + "exceed_action": "exceed_action_value", + "exceed_redirect_options": { + "target": "target_value", + "type_": "type__value", + }, + "rate_limit_threshold": {}, + }, + "redirect_options": {}, + } + ], + "self_link": "self_link_value", + "short_name": "short_name_value", + "type_": "type__value", + "user_defined_fields": [ + { + "base": "base_value", + "mask": "mask_value", + "name": "name_value", + "offset": 647, + "size": 443, + } + ], + } + # 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.PatchOrganizationSecurityPolicyRequest.meta.fields[ + "security_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[ + "security_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["security_policy_resource"][field])): + del request_init["security_policy_resource"][field][i][subfield] + else: + del request_init["security_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.patch(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_patch_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_patch" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_patch_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_patch" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.PatchOrganizationSecurityPolicyRequest.pb( + compute.PatchOrganizationSecurityPolicyRequest() + ) + 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.PatchOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.patch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_patch_rule_rest_bad_request( + request_type=compute.PatchRuleOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.patch_rule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.PatchRuleOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_patch_rule_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "sample1"} + request_init["security_policy_rule_resource"] = { + "action": "action_value", + "description": "description_value", + "header_action": { + "request_headers_to_adds": [ + { + "header_name": "header_name_value", + "header_value": "header_value_value", + } + ] + }, + "kind": "kind_value", + "match": { + "config": { + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"] + }, + "expr": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "expr_options": { + "recaptcha_options": { + "action_token_site_keys": [ + "action_token_site_keys_value1", + "action_token_site_keys_value2", + ], + "session_token_site_keys": [ + "session_token_site_keys_value1", + "session_token_site_keys_value2", + ], + } + }, + "versioned_expr": "versioned_expr_value", + }, + "network_match": { + "dest_ip_ranges": ["dest_ip_ranges_value1", "dest_ip_ranges_value2"], + "dest_ports": ["dest_ports_value1", "dest_ports_value2"], + "ip_protocols": ["ip_protocols_value1", "ip_protocols_value2"], + "src_asns": [861, 862], + "src_ip_ranges": ["src_ip_ranges_value1", "src_ip_ranges_value2"], + "src_ports": ["src_ports_value1", "src_ports_value2"], + "src_region_codes": ["src_region_codes_value1", "src_region_codes_value2"], + "user_defined_fields": [ + {"name": "name_value", "values": ["values_value1", "values_value2"]} + ], + }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, + "preview": True, + "priority": 898, + "rate_limit_options": { + "ban_duration_sec": 1680, + "ban_threshold": {"count": 553, "interval_sec": 1279}, + "conform_action": "conform_action_value", + "enforce_on_key": "enforce_on_key_value", + "enforce_on_key_configs": [ + { + "enforce_on_key_name": "enforce_on_key_name_value", + "enforce_on_key_type": "enforce_on_key_type_value", + } + ], + "enforce_on_key_name": "enforce_on_key_name_value", + "exceed_action": "exceed_action_value", + "exceed_redirect_options": { + "target": "target_value", + "type_": "type__value", + }, + "rate_limit_threshold": {}, + }, + "redirect_options": {}, + } + # 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.PatchRuleOrganizationSecurityPolicyRequest.meta.fields[ + "security_policy_rule_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[ + "security_policy_rule_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["security_policy_rule_resource"][field]) + ): + del request_init["security_policy_rule_resource"][field][i][ + subfield + ] + else: + del request_init["security_policy_rule_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.patch_rule(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_patch_rule_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_patch_rule" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_patch_rule_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_patch_rule" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.PatchRuleOrganizationSecurityPolicyRequest.pb( + compute.PatchRuleOrganizationSecurityPolicyRequest() + ) + 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.PatchRuleOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.patch_rule( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_remove_association_rest_bad_request( + request_type=compute.RemoveAssociationOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.remove_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.RemoveAssociationOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_remove_association_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.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.remove_association(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_remove_association_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, + "post_remove_association", + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_remove_association_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_remove_association" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.RemoveAssociationOrganizationSecurityPolicyRequest.pb( + compute.RemoveAssociationOrganizationSecurityPolicyRequest() + ) + 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.RemoveAssociationOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.remove_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_remove_rule_rest_bad_request( + request_type=compute.RemoveRuleOrganizationSecurityPolicyRequest, +): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.remove_rule(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.RemoveRuleOrganizationSecurityPolicyRequest, + dict, + ], +) +def test_remove_rule_rest_call_success(request_type): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"security_policy": "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.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.remove_rule(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_remove_rule_rest_interceptors(null_interceptor): + transport = transports.OrganizationSecurityPoliciesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationSecurityPoliciesRestInterceptor(), + ) + client = OrganizationSecurityPoliciesClient(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.OrganizationSecurityPoliciesRestInterceptor, "post_remove_rule" + ) as post, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, + "post_remove_rule_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationSecurityPoliciesRestInterceptor, "pre_remove_rule" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.RemoveRuleOrganizationSecurityPolicyRequest.pb( + compute.RemoveRuleOrganizationSecurityPolicyRequest() + ) + 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.RemoveRuleOrganizationSecurityPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.remove_rule( + 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 = OrganizationSecurityPoliciesClient( + 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_add_association_unary_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_association), "__call__") as call: + client.add_association_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.AddAssociationOrganizationSecurityPolicyRequest() + + 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_add_rule_unary_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_rule), "__call__") as call: + client.add_rule_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.AddRuleOrganizationSecurityPolicyRequest() + + 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_copy_rules_unary_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.copy_rules), "__call__") as call: + client.copy_rules_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CopyRulesOrganizationSecurityPolicyRequest() + + 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 = OrganizationSecurityPoliciesClient( + 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.DeleteOrganizationSecurityPolicyRequest() + + 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 = OrganizationSecurityPoliciesClient( + 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.GetOrganizationSecurityPolicyRequest() + + 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_association_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_association), "__call__") as call: + client.get_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetAssociationOrganizationSecurityPolicyRequest() + + 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_rule_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_rule), "__call__") as call: + client.get_rule(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetRuleOrganizationSecurityPolicyRequest() + + 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 = OrganizationSecurityPoliciesClient( + 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.InsertOrganizationSecurityPolicyRequest() + + 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 = OrganizationSecurityPoliciesClient( + 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.ListOrganizationSecurityPoliciesRequest() + + 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_associations_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_associations), "__call__" + ) as call: + client.list_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ListAssociationsOrganizationSecurityPolicyRequest() + + 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_preconfigured_expression_sets_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_preconfigured_expression_sets), "__call__" + ) as call: + client.list_preconfigured_expression_sets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + compute.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest() + ) + + 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_move_unary_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.move), "__call__") as call: + client.move_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.MoveOrganizationSecurityPolicyRequest() + + 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_patch_unary_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.patch), "__call__") as call: + client.patch_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PatchOrganizationSecurityPolicyRequest() + + 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_patch_rule_unary_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.patch_rule), "__call__") as call: + client.patch_rule_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PatchRuleOrganizationSecurityPolicyRequest() + + 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_remove_association_unary_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_association), "__call__" + ) as call: + client.remove_association_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.RemoveAssociationOrganizationSecurityPolicyRequest() + + 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_remove_rule_unary_empty_call_rest(): + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_rule), "__call__") as call: + client.remove_rule_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.RemoveRuleOrganizationSecurityPolicyRequest() + + assert args[0] == request_msg + + +def test_organization_security_policies_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OrganizationSecurityPoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_organization_security_policies_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.organization_security_policies.transports.OrganizationSecurityPoliciesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.OrganizationSecurityPoliciesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "add_association", + "add_rule", + "copy_rules", + "delete", + "get", + "get_association", + "get_rule", + "insert", + "list", + "list_associations", + "list_preconfigured_expression_sets", + "move", + "patch", + "patch_rule", + "remove_association", + "remove_rule", + ) + 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_organization_security_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.organization_security_policies.transports.OrganizationSecurityPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationSecurityPoliciesTransport( + 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_organization_security_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.organization_security_policies.transports.OrganizationSecurityPoliciesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationSecurityPoliciesTransport() + adc.assert_called_once() + + +def test_organization_security_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) + OrganizationSecurityPoliciesClient() + 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_organization_security_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.OrganizationSecurityPoliciesRestTransport( + 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_organization_security_policies_host_no_port(transport_name): + client = OrganizationSecurityPoliciesClient( + 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_organization_security_policies_host_with_port(transport_name): + client = OrganizationSecurityPoliciesClient( + 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_organization_security_policies_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OrganizationSecurityPoliciesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OrganizationSecurityPoliciesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.add_association._session + session2 = client2.transport.add_association._session + assert session1 != session2 + session1 = client1.transport.add_rule._session + session2 = client2.transport.add_rule._session + assert session1 != session2 + session1 = client1.transport.copy_rules._session + session2 = client2.transport.copy_rules._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.get_association._session + session2 = client2.transport.get_association._session + assert session1 != session2 + session1 = client1.transport.get_rule._session + session2 = client2.transport.get_rule._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.list_associations._session + session2 = client2.transport.list_associations._session + assert session1 != session2 + session1 = client1.transport.list_preconfigured_expression_sets._session + session2 = client2.transport.list_preconfigured_expression_sets._session + assert session1 != session2 + session1 = client1.transport.move._session + session2 = client2.transport.move._session + assert session1 != session2 + session1 = client1.transport.patch._session + session2 = client2.transport.patch._session + assert session1 != session2 + session1 = client1.transport.patch_rule._session + session2 = client2.transport.patch_rule._session + assert session1 != session2 + session1 = client1.transport.remove_association._session + session2 = client2.transport.remove_association._session + assert session1 != session2 + session1 = client1.transport.remove_rule._session + session2 = client2.transport.remove_rule._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = OrganizationSecurityPoliciesClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = OrganizationSecurityPoliciesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationSecurityPoliciesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = OrganizationSecurityPoliciesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = OrganizationSecurityPoliciesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationSecurityPoliciesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = OrganizationSecurityPoliciesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = OrganizationSecurityPoliciesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationSecurityPoliciesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = OrganizationSecurityPoliciesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = OrganizationSecurityPoliciesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationSecurityPoliciesClient.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 = OrganizationSecurityPoliciesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = OrganizationSecurityPoliciesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationSecurityPoliciesClient.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.OrganizationSecurityPoliciesTransport, "_prep_wrapped_messages" + ) as prep: + client = OrganizationSecurityPoliciesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.OrganizationSecurityPoliciesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = OrganizationSecurityPoliciesClient.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 = OrganizationSecurityPoliciesClient( + 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 = OrganizationSecurityPoliciesClient( + 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", + [ + ( + OrganizationSecurityPoliciesClient, + transports.OrganizationSecurityPoliciesRestTransport, + ), + ], +) +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_preview_features.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_preview_features.py new file mode 100644 index 000000000000..675a5a88ea4a --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_preview_features.py @@ -0,0 +1,2863 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +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 + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation # type: ignore +from google.api_core import retry as retries +import google.auth +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.preview_features import ( + PreviewFeaturesClient, + 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" + + assert PreviewFeaturesClient._get_default_mtls_endpoint(None) is None + assert ( + PreviewFeaturesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + PreviewFeaturesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + PreviewFeaturesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + PreviewFeaturesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + PreviewFeaturesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +def test__read_environment_variables(): + assert PreviewFeaturesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert PreviewFeaturesClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert PreviewFeaturesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + PreviewFeaturesClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert PreviewFeaturesClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert PreviewFeaturesClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert PreviewFeaturesClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + PreviewFeaturesClient._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 PreviewFeaturesClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert PreviewFeaturesClient._get_client_cert_source(None, False) is None + assert ( + PreviewFeaturesClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + PreviewFeaturesClient._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 ( + PreviewFeaturesClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + PreviewFeaturesClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + PreviewFeaturesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PreviewFeaturesClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = PreviewFeaturesClient._DEFAULT_UNIVERSE + default_endpoint = PreviewFeaturesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = PreviewFeaturesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + PreviewFeaturesClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + PreviewFeaturesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == PreviewFeaturesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + PreviewFeaturesClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + PreviewFeaturesClient._get_api_endpoint(None, None, default_universe, "always") + == PreviewFeaturesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + PreviewFeaturesClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == PreviewFeaturesClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + PreviewFeaturesClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + PreviewFeaturesClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + PreviewFeaturesClient._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 ( + PreviewFeaturesClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + PreviewFeaturesClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + PreviewFeaturesClient._get_universe_domain(None, None) + == PreviewFeaturesClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + PreviewFeaturesClient._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 = PreviewFeaturesClient(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 = PreviewFeaturesClient(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", + [ + (PreviewFeaturesClient, "rest"), + ], +) +def test_preview_features_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.PreviewFeaturesRestTransport, "rest"), + ], +) +def test_preview_features_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", + [ + (PreviewFeaturesClient, "rest"), + ], +) +def test_preview_features_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_preview_features_client_get_transport_class(): + transport = PreviewFeaturesClient.get_transport_class() + available_transports = [ + transports.PreviewFeaturesRestTransport, + ] + assert transport in available_transports + + transport = PreviewFeaturesClient.get_transport_class("rest") + assert transport == transports.PreviewFeaturesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (PreviewFeaturesClient, transports.PreviewFeaturesRestTransport, "rest"), + ], +) +@mock.patch.object( + PreviewFeaturesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PreviewFeaturesClient), +) +def test_preview_features_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(PreviewFeaturesClient, "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(PreviewFeaturesClient, "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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # 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", + [ + ( + PreviewFeaturesClient, + transports.PreviewFeaturesRestTransport, + "rest", + "true", + ), + ( + PreviewFeaturesClient, + transports.PreviewFeaturesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + PreviewFeaturesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PreviewFeaturesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_preview_features_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", [PreviewFeaturesClient]) +@mock.patch.object( + PreviewFeaturesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PreviewFeaturesClient), +) +def test_preview_features_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_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`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [PreviewFeaturesClient]) +@mock.patch.object( + PreviewFeaturesClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(PreviewFeaturesClient), +) +def test_preview_features_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = PreviewFeaturesClient._DEFAULT_UNIVERSE + default_endpoint = PreviewFeaturesClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = PreviewFeaturesClient._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", + [ + (PreviewFeaturesClient, transports.PreviewFeaturesRestTransport, "rest"), + ], +) +def test_preview_features_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", + [ + (PreviewFeaturesClient, transports.PreviewFeaturesRestTransport, "rest", None), + ], +) +def test_preview_features_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_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 = PreviewFeaturesClient( + 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.GetPreviewFeatureRequest): + transport_class = transports.PreviewFeaturesRestTransport + + request_init = {} + request_init["preview_feature"] = "" + 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["previewFeature"] = "preview_feature_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 "previewFeature" in jsonified_request + assert jsonified_request["previewFeature"] == "preview_feature_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = PreviewFeaturesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.PreviewFeature() + # 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.PreviewFeature.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 expected_params == actual_params + + +def test_get_rest_unset_required_fields(): + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "previewFeature", + "project", + ) + ) + ) + + +def test_get_rest_flattened(): + client = PreviewFeaturesClient( + 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.PreviewFeature() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "preview_feature": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + preview_feature="preview_feature_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.PreviewFeature.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/previewFeatures/{preview_feature}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = PreviewFeaturesClient( + 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.GetPreviewFeatureRequest(), + project="project_value", + preview_feature="preview_feature_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 = PreviewFeaturesClient( + 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.ListPreviewFeaturesRequest): + transport_class = transports.PreviewFeaturesRestTransport + + 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 = PreviewFeaturesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.PreviewFeatureList() + # 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.PreviewFeatureList.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 expected_params == actual_params + + +def test_list_rest_unset_required_fields(): + transport = transports.PreviewFeaturesRestTransport( + 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 = PreviewFeaturesClient( + 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.PreviewFeatureList() + + # 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.PreviewFeatureList.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/previewFeatures" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = PreviewFeaturesClient( + 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.ListPreviewFeaturesRequest(), + project="project_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = PreviewFeaturesClient( + 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.PreviewFeatureList( + items=[ + compute.PreviewFeature(), + compute.PreviewFeature(), + compute.PreviewFeature(), + ], + next_page_token="abc", + ), + compute.PreviewFeatureList( + items=[], + next_page_token="def", + ), + compute.PreviewFeatureList( + items=[ + compute.PreviewFeature(), + ], + next_page_token="ghi", + ), + compute.PreviewFeatureList( + items=[ + compute.PreviewFeature(), + compute.PreviewFeature(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.PreviewFeatureList.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.PreviewFeature) 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 = PreviewFeaturesClient( + 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.UpdatePreviewFeatureRequest): + transport_class = transports.PreviewFeaturesRestTransport + + request_init = {} + request_init["preview_feature"] = "" + 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["previewFeature"] = "preview_feature_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 "previewFeature" in jsonified_request + assert jsonified_request["previewFeature"] == "preview_feature_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = PreviewFeaturesClient( + 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 expected_params == actual_params + + +def test_update_rest_unset_required_fields(): + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "previewFeature", + "previewFeatureResource", + "project", + ) + ) + ) + + +def test_update_rest_flattened(): + client = PreviewFeaturesClient( + 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", "preview_feature": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + preview_feature="preview_feature_value", + preview_feature_resource=compute.PreviewFeature( + activation_status="activation_status_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/previewFeatures/{preview_feature}" + % client.transport._host, + args[1], + ) + + +def test_update_rest_flattened_error(transport: str = "rest"): + client = PreviewFeaturesClient( + 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.UpdatePreviewFeatureRequest(), + project="project_value", + preview_feature="preview_feature_value", + preview_feature_resource=compute.PreviewFeature( + activation_status="activation_status_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 = PreviewFeaturesClient( + 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.UpdatePreviewFeatureRequest, +): + transport_class = transports.PreviewFeaturesRestTransport + + request_init = {} + request_init["preview_feature"] = "" + 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["previewFeature"] = "preview_feature_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 "previewFeature" in jsonified_request + assert jsonified_request["previewFeature"] == "preview_feature_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = PreviewFeaturesClient( + 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 expected_params == actual_params + + +def test_update_unary_rest_unset_required_fields(): + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "previewFeature", + "previewFeatureResource", + "project", + ) + ) + ) + + +def test_update_unary_rest_flattened(): + client = PreviewFeaturesClient( + 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", "preview_feature": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + preview_feature="preview_feature_value", + preview_feature_resource=compute.PreviewFeature( + activation_status="activation_status_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/previewFeatures/{preview_feature}" + % client.transport._host, + args[1], + ) + + +def test_update_unary_rest_flattened_error(transport: str = "rest"): + client = PreviewFeaturesClient( + 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.UpdatePreviewFeatureRequest(), + project="project_value", + preview_feature="preview_feature_value", + preview_feature_resource=compute.PreviewFeature( + activation_status="activation_status_value" + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PreviewFeaturesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PreviewFeaturesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PreviewFeaturesClient( + 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 = PreviewFeaturesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PreviewFeaturesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PreviewFeaturesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PreviewFeaturesRestTransport, + ], +) +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 = PreviewFeaturesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetPreviewFeatureRequest): + client = PreviewFeaturesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "preview_feature": "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.GetPreviewFeatureRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = PreviewFeaturesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "preview_feature": "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.PreviewFeature( + activation_status="activation_status_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + kind="kind_value", + name="name_value", + self_link="self_link_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.PreviewFeature.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.PreviewFeature) + assert response.activation_status == "activation_status_value" + 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" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PreviewFeaturesRestInterceptor(), + ) + client = PreviewFeaturesClient(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.PreviewFeaturesRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.PreviewFeaturesRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PreviewFeaturesRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetPreviewFeatureRequest.pb( + compute.GetPreviewFeatureRequest() + ) + 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.PreviewFeature.to_json(compute.PreviewFeature()) + req.return_value.content = return_value + + request = compute.GetPreviewFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.PreviewFeature() + post_with_metadata.return_value = compute.PreviewFeature(), 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.ListPreviewFeaturesRequest): + client = PreviewFeaturesClient( + 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.ListPreviewFeaturesRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = PreviewFeaturesClient( + 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.PreviewFeatureList( + 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.PreviewFeatureList.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.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PreviewFeaturesRestInterceptor(), + ) + client = PreviewFeaturesClient(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.PreviewFeaturesRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.PreviewFeaturesRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PreviewFeaturesRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListPreviewFeaturesRequest.pb( + compute.ListPreviewFeaturesRequest() + ) + 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.PreviewFeatureList.to_json(compute.PreviewFeatureList()) + req.return_value.content = return_value + + request = compute.ListPreviewFeaturesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.PreviewFeatureList() + post_with_metadata.return_value = compute.PreviewFeatureList(), 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.UpdatePreviewFeatureRequest): + client = PreviewFeaturesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "preview_feature": "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.UpdatePreviewFeatureRequest, + dict, + ], +) +def test_update_rest_call_success(request_type): + client = PreviewFeaturesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "preview_feature": "sample2"} + request_init["preview_feature_resource"] = { + "activation_status": "activation_status_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "rollout_operation": { + "rollout_input": { + "name": "name_value", + "predefined_rollout_plan": "predefined_rollout_plan_value", + } + }, + "self_link": "self_link_value", + "status": { + "description": "description_value", + "help_link": "help_link_value", + "release_status": { + "stage": "stage_value", + "update_date": {"day": 318, "month": 550, "year": 433}, + }, + }, + } + # 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.UpdatePreviewFeatureRequest.meta.fields[ + "preview_feature_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[ + "preview_feature_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["preview_feature_resource"][field])): + del request_init["preview_feature_resource"][field][i][subfield] + else: + del request_init["preview_feature_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.PreviewFeaturesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PreviewFeaturesRestInterceptor(), + ) + client = PreviewFeaturesClient(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.PreviewFeaturesRestInterceptor, "post_update" + ) as post, mock.patch.object( + transports.PreviewFeaturesRestInterceptor, "post_update_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.PreviewFeaturesRestInterceptor, "pre_update" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.UpdatePreviewFeatureRequest.pb( + compute.UpdatePreviewFeatureRequest() + ) + 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.UpdatePreviewFeatureRequest() + 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 = PreviewFeaturesClient( + 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_get_empty_call_rest(): + client = PreviewFeaturesClient( + 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.GetPreviewFeatureRequest() + + 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 = PreviewFeaturesClient( + 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.ListPreviewFeaturesRequest() + + 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 = PreviewFeaturesClient( + 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.UpdatePreviewFeatureRequest() + + assert args[0] == request_msg + + +def test_preview_features_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PreviewFeaturesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_preview_features_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.preview_features.transports.PreviewFeaturesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PreviewFeaturesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get", + "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_preview_features_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.preview_features.transports.PreviewFeaturesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PreviewFeaturesTransport( + 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_preview_features_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.preview_features.transports.PreviewFeaturesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PreviewFeaturesTransport() + adc.assert_called_once() + + +def test_preview_features_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) + PreviewFeaturesClient() + 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_preview_features_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.PreviewFeaturesRestTransport( + 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_preview_features_host_no_port(transport_name): + client = PreviewFeaturesClient( + 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_preview_features_host_with_port(transport_name): + client = PreviewFeaturesClient( + 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_preview_features_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PreviewFeaturesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PreviewFeaturesClient( + credentials=creds2, + transport=transport_name, + ) + 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 + 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 = PreviewFeaturesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = PreviewFeaturesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PreviewFeaturesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = PreviewFeaturesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = PreviewFeaturesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PreviewFeaturesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = PreviewFeaturesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = PreviewFeaturesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PreviewFeaturesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = PreviewFeaturesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = PreviewFeaturesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PreviewFeaturesClient.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 = PreviewFeaturesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = PreviewFeaturesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PreviewFeaturesClient.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.PreviewFeaturesTransport, "_prep_wrapped_messages" + ) as prep: + client = PreviewFeaturesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.PreviewFeaturesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = PreviewFeaturesClient.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 = PreviewFeaturesClient( + 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 = PreviewFeaturesClient( + 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", + [ + (PreviewFeaturesClient, transports.PreviewFeaturesRestTransport), + ], +) +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_region_disks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disks.py index ea653eca53f0..4178d44bbf18 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disks.py @@ -7779,6 +7779,7 @@ def test_create_snapshot_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "location_hint": "location_hint_value", "name": "name_value", + "params": {"resource_manager_tags": {}}, "satisfies_pzi": True, "satisfies_pzs": True, "self_link": "self_link_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py index dfb6cfdbfdb3..020132b93123 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py @@ -5414,6 +5414,7 @@ def test_get_rest_call_success(request_type): name="name_value", region="region_value", self_link="self_link_value", + short_name="short_name_value", type_="type__value", ) @@ -5440,6 +5441,7 @@ def test_get_rest_call_success(request_type): assert response.name == "name_value" assert response.region == "region_value" assert response.self_link == "self_link_value" + assert response.short_name == "short_name_value" assert response.type_ == "type__value" @@ -5724,6 +5726,23 @@ def test_insert_rest_call_success(request_type): "user_ip_request_headers_value2", ], }, + "associations": [ + { + "attachment_id": "attachment_id_value", + "display_name": "display_name_value", + "excluded_folders": [ + "excluded_folders_value1", + "excluded_folders_value2", + ], + "excluded_projects": [ + "excluded_projects_value1", + "excluded_projects_value2", + ], + "name": "name_value", + "security_policy_id": "security_policy_id_value", + "short_name": "short_name_value", + } + ], "creation_timestamp": "creation_timestamp_value", "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, "description": "description_value", @@ -5838,6 +5857,7 @@ def test_insert_rest_call_success(request_type): } ], "self_link": "self_link_value", + "short_name": "short_name_value", "type_": "type__value", "user_defined_fields": [ { @@ -6261,6 +6281,23 @@ def test_patch_rest_call_success(request_type): "user_ip_request_headers_value2", ], }, + "associations": [ + { + "attachment_id": "attachment_id_value", + "display_name": "display_name_value", + "excluded_folders": [ + "excluded_folders_value1", + "excluded_folders_value2", + ], + "excluded_projects": [ + "excluded_projects_value1", + "excluded_projects_value2", + ], + "name": "name_value", + "security_policy_id": "security_policy_id_value", + "short_name": "short_name_value", + } + ], "creation_timestamp": "creation_timestamp_value", "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, "description": "description_value", @@ -6375,6 +6412,7 @@ def test_patch_rest_call_success(request_type): } ], "self_link": "self_link_value", + "short_name": "short_name_value", "type_": "type__value", "user_defined_fields": [ { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservation_sub_blocks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservation_sub_blocks.py index f79af8cce967..7a4fabe7eb6b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservation_sub_blocks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservation_sub_blocks.py @@ -1933,6 +1933,456 @@ def test_perform_maintenance_unary_rest_flattened_error(transport: str = "rest") ) +def test_report_faulty_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 = ReservationSubBlocksClient( + 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.report_faulty 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.report_faulty] = mock_rpc + + request = {} + client.report_faulty(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.report_faulty(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_report_faulty_rest_required_fields( + request_type=compute.ReportFaultyReservationSubBlockRequest, +): + transport_class = transports.ReservationSubBlocksRestTransport + + request_init = {} + request_init["parent_name"] = "" + request_init["project"] = "" + request_init["reservation_sub_block"] = "" + request_init["zone"] = "" + 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() + ).report_faulty._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parentName"] = "parent_name_value" + jsonified_request["project"] = "project_value" + jsonified_request["reservationSubBlock"] = "reservation_sub_block_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_faulty._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 "parentName" in jsonified_request + assert jsonified_request["parentName"] == "parent_name_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "reservationSubBlock" in jsonified_request + assert jsonified_request["reservationSubBlock"] == "reservation_sub_block_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = ReservationSubBlocksClient( + 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.report_faulty(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_report_faulty_rest_unset_required_fields(): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.report_faulty._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "parentName", + "project", + "reservationSubBlock", + "reservationSubBlocksReportFaultyRequestResource", + "zone", + ) + ) + ) + + +def test_report_faulty_rest_flattened(): + client = ReservationSubBlocksClient( + 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", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + reservation_sub_blocks_report_faulty_request_resource=compute.ReservationSubBlocksReportFaultyRequest( + disruption_schedule="disruption_schedule_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.report_faulty(**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}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty" + % client.transport._host, + args[1], + ) + + +def test_report_faulty_rest_flattened_error(transport: str = "rest"): + client = ReservationSubBlocksClient( + 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.report_faulty( + compute.ReportFaultyReservationSubBlockRequest(), + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + reservation_sub_blocks_report_faulty_request_resource=compute.ReservationSubBlocksReportFaultyRequest( + disruption_schedule="disruption_schedule_value" + ), + ) + + +def test_report_faulty_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 = ReservationSubBlocksClient( + 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.report_faulty 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.report_faulty] = mock_rpc + + request = {} + client.report_faulty_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.report_faulty_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_report_faulty_unary_rest_required_fields( + request_type=compute.ReportFaultyReservationSubBlockRequest, +): + transport_class = transports.ReservationSubBlocksRestTransport + + request_init = {} + request_init["parent_name"] = "" + request_init["project"] = "" + request_init["reservation_sub_block"] = "" + request_init["zone"] = "" + 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() + ).report_faulty._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parentName"] = "parent_name_value" + jsonified_request["project"] = "project_value" + jsonified_request["reservationSubBlock"] = "reservation_sub_block_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_faulty._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 "parentName" in jsonified_request + assert jsonified_request["parentName"] == "parent_name_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "reservationSubBlock" in jsonified_request + assert jsonified_request["reservationSubBlock"] == "reservation_sub_block_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = ReservationSubBlocksClient( + 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.report_faulty_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_report_faulty_unary_rest_unset_required_fields(): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.report_faulty._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "parentName", + "project", + "reservationSubBlock", + "reservationSubBlocksReportFaultyRequestResource", + "zone", + ) + ) + ) + + +def test_report_faulty_unary_rest_flattened(): + client = ReservationSubBlocksClient( + 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", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + reservation_sub_blocks_report_faulty_request_resource=compute.ReservationSubBlocksReportFaultyRequest( + disruption_schedule="disruption_schedule_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.report_faulty_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}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty" + % client.transport._host, + args[1], + ) + + +def test_report_faulty_unary_rest_flattened_error(transport: str = "rest"): + client = ReservationSubBlocksClient( + 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.report_faulty_unary( + compute.ReportFaultyReservationSubBlockRequest(), + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + reservation_sub_blocks_report_faulty_request_resource=compute.ReservationSubBlocksReportFaultyRequest( + disruption_schedule="disruption_schedule_value" + ), + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ReservationSubBlocksRestTransport( @@ -2468,6 +2918,275 @@ def test_perform_maintenance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_report_faulty_rest_bad_request( + request_type=compute.ReportFaultyReservationSubBlockRequest, +): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + 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.report_faulty(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ReportFaultyReservationSubBlockRequest, + dict, + ], +) +def test_report_faulty_rest_call_success(request_type): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + request_init["reservation_sub_blocks_report_faulty_request_resource"] = { + "disruption_schedule": "disruption_schedule_value", + "failure_component": "failure_component_value", + "fault_reasons": [ + {"behavior": "behavior_value", "description": "description_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.ReportFaultyReservationSubBlockRequest.meta.fields[ + "reservation_sub_blocks_report_faulty_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[ + "reservation_sub_blocks_report_faulty_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[ + "reservation_sub_blocks_report_faulty_request_resource" + ][field] + ), + ): + del request_init[ + "reservation_sub_blocks_report_faulty_request_resource" + ][field][i][subfield] + else: + del request_init[ + "reservation_sub_blocks_report_faulty_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.report_faulty(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_report_faulty_rest_interceptors(null_interceptor): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationSubBlocksRestInterceptor(), + ) + client = ReservationSubBlocksClient(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.ReservationSubBlocksRestInterceptor, "post_report_faulty" + ) as post, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, + "post_report_faulty_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, "pre_report_faulty" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ReportFaultyReservationSubBlockRequest.pb( + compute.ReportFaultyReservationSubBlockRequest() + ) + 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.ReportFaultyReservationSubBlockRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.report_faulty( + 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 = ReservationSubBlocksClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2537,6 +3256,26 @@ def test_perform_maintenance_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_report_faulty_unary_empty_call_rest(): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.report_faulty), "__call__") as call: + client.report_faulty_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ReportFaultyReservationSubBlockRequest() + + assert args[0] == request_msg + + def test_reservation_sub_blocks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -2562,6 +3301,7 @@ def test_reservation_sub_blocks_base_transport(): "get", "list", "perform_maintenance", + "report_faulty", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2708,6 +3448,9 @@ def test_reservation_sub_blocks_client_transport_session_collision(transport_nam session1 = client1.transport.perform_maintenance._session session2 = client2.transport.perform_maintenance._session assert session1 != session2 + session1 = client1.transport.report_faulty._session + session2 = client2.transport.report_faulty._session + assert session1 != session2 def test_common_billing_account_path(): diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py index 7bdf61c786d0..3fd887e00d73 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py @@ -5805,6 +5805,7 @@ def test_get_rest_call_success(request_type): name="name_value", region="region_value", self_link="self_link_value", + short_name="short_name_value", type_="type__value", ) @@ -5831,6 +5832,7 @@ def test_get_rest_call_success(request_type): assert response.name == "name_value" assert response.region == "region_value" assert response.self_link == "self_link_value" + assert response.short_name == "short_name_value" assert response.type_ == "type__value" @@ -6103,6 +6105,23 @@ def test_insert_rest_call_success(request_type): "user_ip_request_headers_value2", ], }, + "associations": [ + { + "attachment_id": "attachment_id_value", + "display_name": "display_name_value", + "excluded_folders": [ + "excluded_folders_value1", + "excluded_folders_value2", + ], + "excluded_projects": [ + "excluded_projects_value1", + "excluded_projects_value2", + ], + "name": "name_value", + "security_policy_id": "security_policy_id_value", + "short_name": "short_name_value", + } + ], "creation_timestamp": "creation_timestamp_value", "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, "description": "description_value", @@ -6217,6 +6236,7 @@ def test_insert_rest_call_success(request_type): } ], "self_link": "self_link_value", + "short_name": "short_name_value", "type_": "type__value", "user_defined_fields": [ { @@ -6774,6 +6794,23 @@ def test_patch_rest_call_success(request_type): "user_ip_request_headers_value2", ], }, + "associations": [ + { + "attachment_id": "attachment_id_value", + "display_name": "display_name_value", + "excluded_folders": [ + "excluded_folders_value1", + "excluded_folders_value2", + ], + "excluded_projects": [ + "excluded_projects_value1", + "excluded_projects_value2", + ], + "name": "name_value", + "security_policy_id": "security_policy_id_value", + "short_name": "short_name_value", + } + ], "creation_timestamp": "creation_timestamp_value", "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, "description": "description_value", @@ -6888,6 +6925,7 @@ def test_patch_rest_call_success(request_type): } ], "self_link": "self_link_value", + "short_name": "short_name_value", "type_": "type__value", "user_defined_fields": [ { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshots.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshots.py index 636dd2d7c181..737e6b545cfc 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshots.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshots.py @@ -3776,6 +3776,7 @@ def test_insert_rest_call_success(request_type): "licenses": ["licenses_value1", "licenses_value2"], "location_hint": "location_hint_value", "name": "name_value", + "params": {"resource_manager_tags": {}}, "satisfies_pzi": True, "satisfies_pzs": True, "self_link": "self_link_value", diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document.py b/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document.py index 85b18d90b2b7..eeb2b7a29522 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document.py @@ -110,6 +110,22 @@ class Document(proto.Message): Parsed layout of the document. chunked_document (google.cloud.documentai_v1.types.Document.ChunkedDocument): Document chunked based on chunking config. + entity_validation_output (google.cloud.documentai_v1.types.Document.EntityValidationOutput): + The entity validation output for the document. This is the + validation output for ``document.entities`` field. + entities_revisions (MutableSequence[google.cloud.documentai_v1.types.Document.EntitiesRevision]): + A list of entity revisions. The entity + revisions are appended to the document in the + processing order. This field can be used for + comparing the entity extraction results at + different stages of the processing. + entities_revision_id (str): + The entity revision id that ``document.entities`` field is + based on. If this field is set and ``entities_revisions`` is + not empty, the entities in ``document.entities`` field are + the entities in the entity revision with this id and + ``document.entity_validation_output`` field is the + ``entity_validation_output`` field in this entity revision. """ class ShardInfo(proto.Message): @@ -2226,6 +2242,113 @@ class ChunkPageFooter(proto.Message): message="Document.ChunkedDocument.Chunk", ) + class EntityValidationOutput(proto.Message): + r"""The output of the validation given the document and the + validation rules. + + Attributes: + validation_results (MutableSequence[google.cloud.documentai_v1.types.Document.EntityValidationOutput.ValidationResult]): + The result of each validation rule. + pass_all_rules (bool): + The overall result of the validation, true if + all applicable rules are valid. + """ + + class ValidationResult(proto.Message): + r"""Validation result for a single validation rule. + + Attributes: + rule_name (str): + The name of the validation rule. + rule_description (str): + The description of the validation rule. + validation_result_type (google.cloud.documentai_v1.types.Document.EntityValidationOutput.ValidationResult.ValidationResultType): + The result of the validation rule. + validation_details (str): + The detailed information of the running the + validation process using the entity from the + document based on the validation rule. + """ + + class ValidationResultType(proto.Enum): + r"""The result of the validation rule. + + Values: + VALIDATION_RESULT_TYPE_UNSPECIFIED (0): + The validation result type is unspecified. + VALIDATION_RESULT_TYPE_VALID (1): + The validation is valid. + VALIDATION_RESULT_TYPE_INVALID (2): + The validation is invalid. + VALIDATION_RESULT_TYPE_SKIPPED (3): + The validation is skipped. + VALIDATION_RESULT_TYPE_NOT_APPLICABLE (4): + The validation is not applicable. + """ + VALIDATION_RESULT_TYPE_UNSPECIFIED = 0 + VALIDATION_RESULT_TYPE_VALID = 1 + VALIDATION_RESULT_TYPE_INVALID = 2 + VALIDATION_RESULT_TYPE_SKIPPED = 3 + VALIDATION_RESULT_TYPE_NOT_APPLICABLE = 4 + + rule_name: str = proto.Field( + proto.STRING, + number=1, + ) + rule_description: str = proto.Field( + proto.STRING, + number=2, + ) + validation_result_type: "Document.EntityValidationOutput.ValidationResult.ValidationResultType" = proto.Field( + proto.ENUM, + number=3, + enum="Document.EntityValidationOutput.ValidationResult.ValidationResultType", + ) + validation_details: str = proto.Field( + proto.STRING, + number=4, + ) + + validation_results: MutableSequence[ + "Document.EntityValidationOutput.ValidationResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Document.EntityValidationOutput.ValidationResult", + ) + pass_all_rules: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class EntitiesRevision(proto.Message): + r"""Entity revision. + + Attributes: + revision_id (str): + The revision id. + entities (MutableSequence[google.cloud.documentai_v1.types.Document.Entity]): + The entities in this revision. + entity_validation_output (google.cloud.documentai_v1.types.Document.EntityValidationOutput): + The entity validation output for this + revision. + """ + + revision_id: str = proto.Field( + proto.STRING, + number=1, + ) + entities: MutableSequence["Document.Entity"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Document.Entity", + ) + entity_validation_output: "Document.EntityValidationOutput" = proto.Field( + proto.MESSAGE, + number=3, + message="Document.EntityValidationOutput", + ) + uri: str = proto.Field( proto.STRING, number=1, @@ -2298,6 +2421,20 @@ class ChunkPageFooter(proto.Message): number=18, message=ChunkedDocument, ) + entity_validation_output: EntityValidationOutput = proto.Field( + proto.MESSAGE, + number=21, + message=EntityValidationOutput, + ) + entities_revisions: MutableSequence[EntitiesRevision] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message=EntitiesRevision, + ) + entities_revision_id: str = proto.Field( + proto.STRING, + number=23, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document_processor_service.py b/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document_processor_service.py index a24388e3126a..1f515258c865 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document_processor_service.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document_processor_service.py @@ -1288,7 +1288,8 @@ class CustomDocumentExtractionOptions(proto.Message): Attributes: training_method (google.cloud.documentai_v1.types.TrainProcessorVersionRequest.CustomDocumentExtractionOptions.TrainingMethod): - Training method to use for CDE training. + Optional. Training method to use for CDE + training. """ class TrainingMethod(proto.Enum):