diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9282ee34d387..0c77c0462c6f 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,90 +1,90 @@ { - "packages/google-ads-admanager": "0.2.1", + "packages/google-ads-admanager": "0.2.2", "packages/google-ads-marketingplatform-admin": "0.1.1", - "packages/google-ai-generativelanguage": "0.6.11", - "packages/google-analytics-admin": "0.23.1", - "packages/google-analytics-data": "0.18.14", + "packages/google-ai-generativelanguage": "0.6.12", + "packages/google-analytics-admin": "0.23.2", + "packages/google-analytics-data": "0.18.15", "packages/google-apps-card": "0.1.5", - "packages/google-apps-chat": "0.1.13", - "packages/google-apps-events-subscriptions": "0.1.3", - "packages/google-apps-meet": "0.1.9", + "packages/google-apps-chat": "0.1.14", + "packages/google-apps-events-subscriptions": "0.1.4", + "packages/google-apps-meet": "0.1.10", "packages/google-apps-script-type": "0.3.11", - "packages/google-area120-tables": "0.11.12", - "packages/google-cloud-access-approval": "1.14.0", - "packages/google-cloud-advisorynotifications": "0.3.11", - "packages/google-cloud-alloydb": "0.3.15", + "packages/google-area120-tables": "0.11.13", + "packages/google-cloud-access-approval": "1.14.1", + "packages/google-cloud-advisorynotifications": "0.3.12", + "packages/google-cloud-alloydb": "0.3.16", "packages/google-cloud-alloydb-connectors": "0.1.7", - "packages/google-cloud-api-gateway": "1.10.0", - "packages/google-cloud-api-keys": "0.5.12", - "packages/google-cloud-apigee-connect": "1.10.0", - "packages/google-cloud-apigee-registry": "0.6.12", - "packages/google-cloud-apihub": "0.2.1", - "packages/google-cloud-appengine-admin": "1.12.0", + "packages/google-cloud-api-gateway": "1.10.1", + "packages/google-cloud-api-keys": "0.5.13", + "packages/google-cloud-apigee-connect": "1.10.1", + "packages/google-cloud-apigee-registry": "0.6.13", + "packages/google-cloud-apihub": "0.2.2", + "packages/google-cloud-appengine-admin": "1.12.1", "packages/google-cloud-appengine-logging": "1.5.0", - "packages/google-cloud-apphub": "0.1.3", + "packages/google-cloud-apphub": "0.1.4", "packages/google-cloud-artifact-registry": "1.13.0", - "packages/google-cloud-asset": "3.27.0", - "packages/google-cloud-assured-workloads": "1.13.0", - "packages/google-cloud-automl": "2.14.0", - "packages/google-cloud-backupdr": "0.1.5", - "packages/google-cloud-bare-metal-solution": "1.8.0", - "packages/google-cloud-batch": "0.17.30", - "packages/google-cloud-beyondcorp-appconnections": "0.4.12", - "packages/google-cloud-beyondcorp-appconnectors": "0.4.12", - "packages/google-cloud-beyondcorp-appgateways": "0.4.12", - "packages/google-cloud-beyondcorp-clientconnectorservices": "0.4.12", - "packages/google-cloud-beyondcorp-clientgateways": "0.4.11", - "packages/google-cloud-bigquery-analyticshub": "0.4.12", - "packages/google-cloud-bigquery-biglake": "0.4.10", - "packages/google-cloud-bigquery-connection": "1.16.0", - "packages/google-cloud-bigquery-data-exchange": "0.5.14", - "packages/google-cloud-bigquery-datapolicies": "0.6.9", - "packages/google-cloud-bigquery-datatransfer": "3.17.0", + "packages/google-cloud-asset": "3.27.1", + "packages/google-cloud-assured-workloads": "1.13.1", + "packages/google-cloud-automl": "2.14.1", + "packages/google-cloud-backupdr": "0.1.6", + "packages/google-cloud-bare-metal-solution": "1.8.1", + "packages/google-cloud-batch": "0.17.31", + "packages/google-cloud-beyondcorp-appconnections": "0.4.13", + "packages/google-cloud-beyondcorp-appconnectors": "0.4.13", + "packages/google-cloud-beyondcorp-appgateways": "0.4.13", + "packages/google-cloud-beyondcorp-clientconnectorservices": "0.4.13", + "packages/google-cloud-beyondcorp-clientgateways": "0.4.12", + "packages/google-cloud-bigquery-analyticshub": "0.4.13", + "packages/google-cloud-bigquery-biglake": "0.4.11", + "packages/google-cloud-bigquery-connection": "1.16.1", + "packages/google-cloud-bigquery-data-exchange": "0.5.15", + "packages/google-cloud-bigquery-datapolicies": "0.6.10", + "packages/google-cloud-bigquery-datatransfer": "3.17.1", "packages/google-cloud-bigquery-logging": "1.5.0", - "packages/google-cloud-bigquery-migration": "0.11.10", - "packages/google-cloud-bigquery-reservation": "1.14.0", - "packages/google-cloud-billing": "1.14.0", - "packages/google-cloud-billing-budgets": "1.15.0", - "packages/google-cloud-binary-authorization": "1.11.0", + "packages/google-cloud-bigquery-migration": "0.11.11", + "packages/google-cloud-bigquery-reservation": "1.14.1", + "packages/google-cloud-billing": "1.14.1", + "packages/google-cloud-billing-budgets": "1.15.1", + "packages/google-cloud-binary-authorization": "1.11.1", "packages/google-cloud-build": "3.27.0", - "packages/google-cloud-certificate-manager": "1.8.0", - "packages/google-cloud-channel": "1.20.0", - "packages/google-cloud-cloudcontrolspartner": "0.2.1", - "packages/google-cloud-commerce-consumer-procurement": "0.1.9", + "packages/google-cloud-certificate-manager": "1.8.1", + "packages/google-cloud-channel": "1.20.1", + "packages/google-cloud-cloudcontrolspartner": "0.2.2", + "packages/google-cloud-commerce-consumer-procurement": "0.1.10", "packages/google-cloud-common": "1.4.0", - "packages/google-cloud-compute": "1.20.0", - "packages/google-cloud-confidentialcomputing": "0.4.12", - "packages/google-cloud-config": "0.1.12", - "packages/google-cloud-contact-center-insights": "1.19.0", + "packages/google-cloud-compute": "1.20.1", + "packages/google-cloud-confidentialcomputing": "0.4.13", + "packages/google-cloud-config": "0.1.13", + "packages/google-cloud-contact-center-insights": "1.19.1", "packages/google-cloud-container": "2.53.0", "packages/google-cloud-containeranalysis": "2.15.0", - "packages/google-cloud-contentwarehouse": "0.7.10", - "packages/google-cloud-data-fusion": "1.11.0", - "packages/google-cloud-data-qna": "0.10.12", - "packages/google-cloud-datacatalog": "3.21.0", - "packages/google-cloud-datacatalog-lineage": "0.3.9", + "packages/google-cloud-contentwarehouse": "0.7.11", + "packages/google-cloud-data-fusion": "1.11.1", + "packages/google-cloud-data-qna": "0.10.13", + "packages/google-cloud-datacatalog": "3.21.1", + "packages/google-cloud-datacatalog-lineage": "0.3.10", "packages/google-cloud-dataflow-client": "0.8.13", - "packages/google-cloud-dataform": "0.5.12", - "packages/google-cloud-datalabeling": "1.11.0", - "packages/google-cloud-dataplex": "2.3.0", - "packages/google-cloud-dataproc": "5.15.0", + "packages/google-cloud-dataform": "0.5.13", + "packages/google-cloud-datalabeling": "1.11.1", + "packages/google-cloud-dataplex": "2.3.1", + "packages/google-cloud-dataproc": "5.15.1", "packages/google-cloud-dataproc-metastore": "1.16.0", - "packages/google-cloud-datastream": "1.10.0", - "packages/google-cloud-deploy": "2.2.0", - "packages/google-cloud-developerconnect": "0.1.3", + "packages/google-cloud-datastream": "1.10.1", + "packages/google-cloud-deploy": "2.3.0", + "packages/google-cloud-developerconnect": "0.1.4", "packages/google-cloud-dialogflow": "2.34.0", "packages/google-cloud-dialogflow-cx": "1.36.0", - "packages/google-cloud-discoveryengine": "0.13.2", + "packages/google-cloud-discoveryengine": "0.13.3", "packages/google-cloud-dlp": "3.25.0", - "packages/google-cloud-dms": "1.10.0", + "packages/google-cloud-dms": "1.10.1", "packages/google-cloud-documentai": "3.0.0", "packages/google-cloud-domains": "1.8.0", - "packages/google-cloud-edgecontainer": "0.5.12", + "packages/google-cloud-edgecontainer": "0.5.13", "packages/google-cloud-edgenetwork": "0.1.12", "packages/google-cloud-enterpriseknowledgegraph": "0.3.12", "packages/google-cloud-essential-contacts": "1.8.0", - "packages/google-cloud-eventarc": "1.12.0", - "packages/google-cloud-eventarc-publishing": "0.6.12", + "packages/google-cloud-eventarc": "1.13.0", + "packages/google-cloud-eventarc-publishing": "0.6.13", "packages/google-cloud-filestore": "1.10.0", "packages/google-cloud-functions": "1.18.0", "packages/google-cloud-gdchardwaremanagement": "0.1.6", @@ -129,9 +129,9 @@ "packages/google-cloud-private-catalog": "0.9.12", "packages/google-cloud-privilegedaccessmanager": "0.1.2", "packages/google-cloud-public-ca": "0.3.13", - "packages/google-cloud-quotas": "0.1.11", + "packages/google-cloud-quotas": "0.1.12", "packages/google-cloud-rapidmigrationassessment": "0.1.10", - "packages/google-cloud-recaptcha-enterprise": "1.23.0", + "packages/google-cloud-recaptcha-enterprise": "1.24.0", "packages/google-cloud-recommendations-ai": "0.10.13", "packages/google-cloud-recommender": "2.16.0", "packages/google-cloud-redis": "2.16.0", @@ -144,11 +144,11 @@ "packages/google-cloud-secret-manager": "2.21.0", "packages/google-cloud-securesourcemanager": "0.1.10", "packages/google-cloud-securitycenter": "1.35.0", - "packages/google-cloud-securitycentermanagement": "0.1.15", - "packages/google-cloud-service-control": "1.13.0", + "packages/google-cloud-securitycentermanagement": "0.1.16", + "packages/google-cloud-service-control": "1.13.1", "packages/google-cloud-service-directory": "1.12.0", - "packages/google-cloud-service-management": "1.10.0", - "packages/google-cloud-service-usage": "1.11.0", + "packages/google-cloud-service-management": "1.10.1", + "packages/google-cloud-service-usage": "1.11.1", "packages/google-cloud-servicehealth": "0.1.7", "packages/google-cloud-shell": "1.10.0", "packages/google-cloud-source-context": "1.6.0", @@ -160,7 +160,7 @@ "packages/google-cloud-talent": "2.14.0", "packages/google-cloud-tasks": "2.17.0", "packages/google-cloud-telcoautomation": "0.2.6", - "packages/google-cloud-texttospeech": "2.20.0", + "packages/google-cloud-texttospeech": "2.21.0", "packages/google-cloud-tpu": "1.19.0", "packages/google-cloud-trace": "1.14.0", "packages/google-cloud-translate": "3.17.0", diff --git a/CHANGELOG.md b/CHANGELOG.md index 329502ab6ea4..ac17d8e5875d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,205 +2,205 @@ Please refer to each API's `CHANGELOG.md` file under the `packages/` directory Changelogs ----- -- [google-ads-admanager==0.2.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ads-admanager/CHANGELOG.md) -- [google-ads-marketingplatform-admin==0.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ads-marketingplatform-admin/CHANGELOG.md) -- [google-ai-generativelanguage==0.6.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ai-generativelanguage/CHANGELOG.md) -- [google-analytics-admin==0.23.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-admin/CHANGELOG.md) -- [google-analytics-data==0.18.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-data/CHANGELOG.md) -- [google-apps-card==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-card/CHANGELOG.md) -- [google-apps-chat==0.1.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-chat/CHANGELOG.md) -- [google-apps-events-subscriptions==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-events-subscriptions/CHANGELOG.md) -- [google-apps-meet==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-meet/CHANGELOG.md) -- [google-apps-script-type==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-script-type/CHANGELOG.md) -- [google-area120-tables==0.11.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-area120-tables/CHANGELOG.md) -- [google-cloud-access-approval==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-access-approval/CHANGELOG.md) -- [google-cloud-advisorynotifications==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-advisorynotifications/CHANGELOG.md) -- [google-cloud-alloydb-connectors==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb-connectors/CHANGELOG.md) -- [google-cloud-alloydb==0.3.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb/CHANGELOG.md) -- [google-cloud-api-gateway==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-gateway/CHANGELOG.md) -- [google-cloud-api-keys==0.5.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-keys/CHANGELOG.md) -- [google-cloud-apigee-connect==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-connect/CHANGELOG.md) -- [google-cloud-apigee-registry==0.6.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-registry/CHANGELOG.md) -- [google-cloud-apihub==0.2.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apihub/CHANGELOG.md) -- [google-cloud-appengine-admin==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-admin/CHANGELOG.md) -- [google-cloud-appengine-logging==1.4.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-logging/CHANGELOG.md) -- [google-cloud-apphub==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apphub/CHANGELOG.md) -- [google-cloud-artifact-registry==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-artifact-registry/CHANGELOG.md) -- [google-cloud-asset==3.26.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-asset/CHANGELOG.md) -- [google-cloud-assured-workloads==1.12.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-assured-workloads/CHANGELOG.md) -- [google-cloud-automl==2.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-automl/CHANGELOG.md) -- [google-cloud-backupdr==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-backupdr/CHANGELOG.md) -- [google-cloud-bare-metal-solution==1.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bare-metal-solution/CHANGELOG.md) -- [google-cloud-batch==0.17.29](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-batch/CHANGELOG.md) -- [google-cloud-beyondcorp-appconnections==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md) -- [google-cloud-beyondcorp-appconnectors==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md) -- [google-cloud-beyondcorp-appgateways==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md) -- [google-cloud-beyondcorp-clientconnectorservices==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md) -- [google-cloud-beyondcorp-clientgateways==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md) -- [google-cloud-bigquery-analyticshub==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md) -- [google-cloud-bigquery-biglake==0.4.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-biglake/CHANGELOG.md) -- [google-cloud-bigquery-connection==1.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-connection/CHANGELOG.md) -- [google-cloud-bigquery-data-exchange==0.5.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md) -- [google-cloud-bigquery-datapolicies==0.6.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md) -- [google-cloud-bigquery-datatransfer==3.16.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md) -- [google-cloud-bigquery-logging==1.4.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-logging/CHANGELOG.md) -- [google-cloud-bigquery-migration==0.11.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-migration/CHANGELOG.md) -- [google-cloud-bigquery-reservation==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-reservation/CHANGELOG.md) -- [google-cloud-billing-budgets==1.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing-budgets/CHANGELOG.md) -- [google-cloud-billing==1.13.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing/CHANGELOG.md) -- [google-cloud-binary-authorization==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-binary-authorization/CHANGELOG.md) -- [google-cloud-build==3.25.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-build/CHANGELOG.md) -- [google-cloud-certificate-manager==1.7.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-certificate-manager/CHANGELOG.md) -- [google-cloud-channel==1.19.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-channel/CHANGELOG.md) -- [google-cloud-cloudcontrolspartner==0.2.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md) -- [google-cloud-commerce-consumer-procurement==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md) -- [google-cloud-common==1.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-common/CHANGELOG.md) -- [google-cloud-compute==1.19.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-compute/CHANGELOG.md) -- [google-cloud-confidentialcomputing==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-confidentialcomputing/CHANGELOG.md) -- [google-cloud-config==0.1.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-config/CHANGELOG.md) -- [google-cloud-contact-center-insights==1.18.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contact-center-insights/CHANGELOG.md) -- [google-cloud-container==2.52.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-container/CHANGELOG.md) -- [google-cloud-containeranalysis==2.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-containeranalysis/CHANGELOG.md) -- [google-cloud-contentwarehouse==0.7.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contentwarehouse/CHANGELOG.md) -- [google-cloud-data-fusion==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-fusion/CHANGELOG.md) -- [google-cloud-data-qna==0.10.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-qna/CHANGELOG.md) -- [google-cloud-datacatalog-lineage==0.3.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog-lineage/CHANGELOG.md) -- [google-cloud-datacatalog==3.20.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog/CHANGELOG.md) -- [google-cloud-dataflow-client==0.8.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataflow-client/CHANGELOG.md) -- [google-cloud-dataform==0.5.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataform/CHANGELOG.md) -- [google-cloud-datalabeling==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datalabeling/CHANGELOG.md) -- [google-cloud-dataplex==2.2.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataplex/CHANGELOG.md) -- [google-cloud-dataproc-metastore==1.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc-metastore/CHANGELOG.md) -- [google-cloud-dataproc==5.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc/CHANGELOG.md) -- [google-cloud-datastream==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datastream/CHANGELOG.md) -- [google-cloud-deploy==2.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-deploy/CHANGELOG.md) -- [google-cloud-developerconnect==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-developerconnect/CHANGELOG.md) -- [google-cloud-dialogflow-cx==1.35.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow-cx/CHANGELOG.md) -- [google-cloud-dialogflow==2.33.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow/CHANGELOG.md) -- [google-cloud-discoveryengine==0.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-discoveryengine/CHANGELOG.md) -- [google-cloud-dlp==3.23.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dlp/CHANGELOG.md) -- [google-cloud-dms==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dms/CHANGELOG.md) -- [google-cloud-documentai==2.33.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-documentai/CHANGELOG.md) -- [google-cloud-domains==1.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-domains/CHANGELOG.md) -- [google-cloud-edgecontainer==0.5.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgecontainer/CHANGELOG.md) -- [google-cloud-edgenetwork==0.1.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgenetwork/CHANGELOG.md) -- [google-cloud-enterpriseknowledgegraph==0.3.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md) -- [google-cloud-essential-contacts==1.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-essential-contacts/CHANGELOG.md) -- [google-cloud-eventarc-publishing==0.6.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc-publishing/CHANGELOG.md) -- [google-cloud-eventarc==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc/CHANGELOG.md) -- [google-cloud-filestore==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-filestore/CHANGELOG.md) -- [google-cloud-functions==1.17.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-functions/CHANGELOG.md) -- [google-cloud-gdchardwaremanagement==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gdchardwaremanagement/CHANGELOG.md) -- [google-cloud-gke-backup==0.5.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-backup/CHANGELOG.md) -- [google-cloud-gke-connect-gateway==0.9.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-connect-gateway/CHANGELOG.md) -- [google-cloud-gke-hub==1.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-hub/CHANGELOG.md) -- [google-cloud-gke-multicloud==0.6.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-multicloud/CHANGELOG.md) -- [google-cloud-gsuiteaddons==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gsuiteaddons/CHANGELOG.md) -- [google-cloud-iam-logging==1.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam-logging/CHANGELOG.md) -- [google-cloud-iam==2.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam/CHANGELOG.md) -- [google-cloud-iap==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iap/CHANGELOG.md) -- [google-cloud-ids==1.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-ids/CHANGELOG.md) -- [google-cloud-kms-inventory==0.2.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms-inventory/CHANGELOG.md) -- [google-cloud-kms==3.0.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms/CHANGELOG.md) -- [google-cloud-language==2.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-language/CHANGELOG.md) -- [google-cloud-life-sciences==0.9.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-life-sciences/CHANGELOG.md) -- [google-cloud-managed-identities==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managed-identities/CHANGELOG.md) -- [google-cloud-managedkafka==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managedkafka/CHANGELOG.md) -- [google-cloud-media-translation==0.11.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-media-translation/CHANGELOG.md) -- [google-cloud-memcache==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-memcache/CHANGELOG.md) -- [google-cloud-migrationcenter==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-migrationcenter/CHANGELOG.md) -- [google-cloud-monitoring-dashboards==2.15.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-dashboards/CHANGELOG.md) -- [google-cloud-monitoring-metrics-scopes==1.6.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md) -- [google-cloud-monitoring==2.22.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring/CHANGELOG.md) -- [google-cloud-netapp==0.3.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-netapp/CHANGELOG.md) -- [google-cloud-network-connectivity==2.4.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-connectivity/CHANGELOG.md) -- [google-cloud-network-management==1.18.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management/CHANGELOG.md) -- [google-cloud-network-security==0.9.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security/CHANGELOG.md) -- [google-cloud-network-services==0.5.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-services/CHANGELOG.md) -- [google-cloud-notebooks==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-notebooks/CHANGELOG.md) -- [google-cloud-optimization==1.8.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-optimization/CHANGELOG.md) -- [google-cloud-oracledatabase==0.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-oracledatabase/CHANGELOG.md) -- [google-cloud-orchestration-airflow==1.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-orchestration-airflow/CHANGELOG.md) -- [google-cloud-os-config==1.17.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-config/CHANGELOG.md) -- [google-cloud-os-login==2.14.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-login/CHANGELOG.md) -- [google-cloud-parallelstore==0.2.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-parallelstore/CHANGELOG.md) -- [google-cloud-phishing-protection==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-phishing-protection/CHANGELOG.md) -- [google-cloud-policy-troubleshooter==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policy-troubleshooter/CHANGELOG.md) -- [google-cloud-policysimulator==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policysimulator/CHANGELOG.md) -- [google-cloud-policytroubleshooter-iam==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md) -- [google-cloud-private-ca==1.12.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-ca/CHANGELOG.md) -- [google-cloud-private-catalog==0.9.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-catalog/CHANGELOG.md) -- [google-cloud-privilegedaccessmanager==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-privilegedaccessmanager/CHANGELOG.md) -- [google-cloud-public-ca==0.3.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-public-ca/CHANGELOG.md) -- [google-cloud-quotas==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-quotas/CHANGELOG.md) -- [google-cloud-rapidmigrationassessment==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md) -- [google-cloud-recaptcha-enterprise==1.22.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md) -- [google-cloud-recommendations-ai==0.10.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommendations-ai/CHANGELOG.md) -- [google-cloud-recommender==2.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommender/CHANGELOG.md) -- [google-cloud-redis-cluster==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis-cluster/CHANGELOG.md) -- [google-cloud-redis==2.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis/CHANGELOG.md) -- [google-cloud-resource-manager==1.12.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-manager/CHANGELOG.md) -- [google-cloud-resource-settings==1.9.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-settings/CHANGELOG.md) -- [google-cloud-retail==1.22.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-retail/CHANGELOG.md) -- [google-cloud-run==0.10.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-run/CHANGELOG.md) -- [google-cloud-scheduler==2.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-scheduler/CHANGELOG.md) -- [google-cloud-secret-manager==2.20.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-secret-manager/CHANGELOG.md) -- [google-cloud-securesourcemanager==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securesourcemanager/CHANGELOG.md) -- [google-cloud-securitycenter==1.34.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter/CHANGELOG.md) -- [google-cloud-securitycentermanagement==0.1.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycentermanagement/CHANGELOG.md) -- [google-cloud-service-control==1.12.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-control/CHANGELOG.md) -- [google-cloud-service-directory==1.11.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-directory/CHANGELOG.md) -- [google-cloud-service-management==1.9.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-management/CHANGELOG.md) -- [google-cloud-service-usage==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-usage/CHANGELOG.md) -- [google-cloud-servicehealth==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-servicehealth/CHANGELOG.md) -- [google-cloud-shell==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-shell/CHANGELOG.md) -- [google-cloud-source-context==1.5.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-source-context/CHANGELOG.md) -- [google-cloud-speech==2.27.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-speech/CHANGELOG.md) -- [google-cloud-storage-control==1.0.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-control/CHANGELOG.md) -- [google-cloud-storage-transfer==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-transfer/CHANGELOG.md) -- [google-cloud-storageinsights==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storageinsights/CHANGELOG.md) -- [google-cloud-support==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-support/CHANGELOG.md) -- [google-cloud-talent==2.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-talent/CHANGELOG.md) -- [google-cloud-tasks==2.16.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tasks/CHANGELOG.md) -- [google-cloud-telcoautomation==0.2.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-telcoautomation/CHANGELOG.md) -- [google-cloud-texttospeech==2.18.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-texttospeech/CHANGELOG.md) -- [google-cloud-tpu==1.18.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tpu/CHANGELOG.md) -- [google-cloud-trace==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-trace/CHANGELOG.md) -- [google-cloud-translate==3.16.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-translate/CHANGELOG.md) -- [google-cloud-video-live-stream==1.8.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-live-stream/CHANGELOG.md) -- [google-cloud-video-stitcher==0.7.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-stitcher/CHANGELOG.md) -- [google-cloud-video-transcoder==1.12.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-transcoder/CHANGELOG.md) -- [google-cloud-videointelligence==2.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-videointelligence/CHANGELOG.md) -- [google-cloud-vision==3.7.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vision/CHANGELOG.md) -- [google-cloud-visionai==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-visionai/CHANGELOG.md) -- [google-cloud-vm-migration==1.8.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vm-migration/CHANGELOG.md) -- [google-cloud-vmwareengine==1.5.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vmwareengine/CHANGELOG.md) -- [google-cloud-vpc-access==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vpc-access/CHANGELOG.md) -- [google-cloud-webrisk==1.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-webrisk/CHANGELOG.md) -- [google-cloud-websecurityscanner==1.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-websecurityscanner/CHANGELOG.md) -- [google-cloud-workflows==1.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workflows/CHANGELOG.md) -- [google-cloud-workstations==0.5.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations/CHANGELOG.md) -- [google-geo-type==0.3.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-geo-type/CHANGELOG.md) -- [google-maps-addressvalidation==0.3.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-addressvalidation/CHANGELOG.md) -- [google-maps-areainsights==0.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-areainsights/CHANGELOG.md) -- [google-maps-fleetengine-delivery==0.2.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine-delivery/CHANGELOG.md) -- [google-maps-fleetengine==0.2.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine/CHANGELOG.md) -- [google-maps-mapsplatformdatasets==0.4.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-mapsplatformdatasets/CHANGELOG.md) -- [google-maps-places==0.1.18](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places/CHANGELOG.md) -- [google-maps-routeoptimization==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routeoptimization/CHANGELOG.md) -- [google-maps-routing==0.6.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routing/CHANGELOG.md) -- [google-maps-solar==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-solar/CHANGELOG.md) -- [google-shopping-css==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-css/CHANGELOG.md) -- [google-shopping-merchant-accounts==0.2.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-accounts/CHANGELOG.md) -- [google-shopping-merchant-conversions==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-conversions/CHANGELOG.md) -- [google-shopping-merchant-datasources==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-datasources/CHANGELOG.md) -- [google-shopping-merchant-inventories==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories/CHANGELOG.md) -- [google-shopping-merchant-lfp==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-lfp/CHANGELOG.md) -- [google-shopping-merchant-notifications==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-notifications/CHANGELOG.md) -- [google-shopping-merchant-products==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-products/CHANGELOG.md) -- [google-shopping-merchant-promotions==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-promotions/CHANGELOG.md) -- [google-shopping-merchant-quota==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-quota/CHANGELOG.md) -- [google-shopping-merchant-reports==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-reports/CHANGELOG.md) -- [google-shopping-type==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-type/CHANGELOG.md) -- [grafeas==1.11.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas/CHANGELOG.md) +- [google-ads-admanager==0.2.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ads-admanager/CHANGELOG.md) +- [google-ads-marketingplatform-admin==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ads-marketingplatform-admin/CHANGELOG.md) +- [google-ai-generativelanguage==0.6.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ai-generativelanguage/CHANGELOG.md) +- [google-analytics-admin==0.23.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-admin/CHANGELOG.md) +- [google-analytics-data==0.18.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-data/CHANGELOG.md) +- [google-apps-card==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-card/CHANGELOG.md) +- [google-apps-chat==0.1.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-chat/CHANGELOG.md) +- [google-apps-events-subscriptions==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-events-subscriptions/CHANGELOG.md) +- [google-apps-meet==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-meet/CHANGELOG.md) +- [google-apps-script-type==0.3.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-script-type/CHANGELOG.md) +- [google-area120-tables==0.11.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-area120-tables/CHANGELOG.md) +- [google-cloud-access-approval==1.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-access-approval/CHANGELOG.md) +- [google-cloud-advisorynotifications==0.3.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-advisorynotifications/CHANGELOG.md) +- [google-cloud-alloydb-connectors==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb-connectors/CHANGELOG.md) +- [google-cloud-alloydb==0.3.15](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb/CHANGELOG.md) +- [google-cloud-api-gateway==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-gateway/CHANGELOG.md) +- [google-cloud-api-keys==0.5.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-keys/CHANGELOG.md) +- [google-cloud-apigee-connect==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-connect/CHANGELOG.md) +- [google-cloud-apigee-registry==0.6.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-registry/CHANGELOG.md) +- [google-cloud-apihub==0.2.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apihub/CHANGELOG.md) +- [google-cloud-appengine-admin==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-admin/CHANGELOG.md) +- [google-cloud-appengine-logging==1.5.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-logging/CHANGELOG.md) +- [google-cloud-apphub==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apphub/CHANGELOG.md) +- [google-cloud-artifact-registry==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-artifact-registry/CHANGELOG.md) +- [google-cloud-asset==3.27.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-asset/CHANGELOG.md) +- [google-cloud-assured-workloads==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-assured-workloads/CHANGELOG.md) +- [google-cloud-automl==2.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-automl/CHANGELOG.md) +- [google-cloud-backupdr==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-backupdr/CHANGELOG.md) +- [google-cloud-bare-metal-solution==1.8.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bare-metal-solution/CHANGELOG.md) +- [google-cloud-batch==0.17.30](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-batch/CHANGELOG.md) +- [google-cloud-beyondcorp-appconnections==0.4.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md) +- [google-cloud-beyondcorp-appconnectors==0.4.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md) +- [google-cloud-beyondcorp-appgateways==0.4.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md) +- [google-cloud-beyondcorp-clientconnectorservices==0.4.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md) +- [google-cloud-beyondcorp-clientgateways==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md) +- [google-cloud-bigquery-analyticshub==0.4.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md) +- [google-cloud-bigquery-biglake==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-biglake/CHANGELOG.md) +- [google-cloud-bigquery-connection==1.16.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-connection/CHANGELOG.md) +- [google-cloud-bigquery-data-exchange==0.5.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md) +- [google-cloud-bigquery-datapolicies==0.6.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md) +- [google-cloud-bigquery-datatransfer==3.17.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md) +- [google-cloud-bigquery-logging==1.5.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-logging/CHANGELOG.md) +- [google-cloud-bigquery-migration==0.11.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-migration/CHANGELOG.md) +- [google-cloud-bigquery-reservation==1.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-reservation/CHANGELOG.md) +- [google-cloud-billing-budgets==1.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing-budgets/CHANGELOG.md) +- [google-cloud-billing==1.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing/CHANGELOG.md) +- [google-cloud-binary-authorization==1.11.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-binary-authorization/CHANGELOG.md) +- [google-cloud-build==3.27.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-build/CHANGELOG.md) +- [google-cloud-certificate-manager==1.8.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-certificate-manager/CHANGELOG.md) +- [google-cloud-channel==1.20.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-channel/CHANGELOG.md) +- [google-cloud-cloudcontrolspartner==0.2.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md) +- [google-cloud-commerce-consumer-procurement==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md) +- [google-cloud-common==1.4.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-common/CHANGELOG.md) +- [google-cloud-compute==1.20.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-compute/CHANGELOG.md) +- [google-cloud-confidentialcomputing==0.4.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-confidentialcomputing/CHANGELOG.md) +- [google-cloud-config==0.1.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-config/CHANGELOG.md) +- [google-cloud-contact-center-insights==1.19.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contact-center-insights/CHANGELOG.md) +- [google-cloud-container==2.53.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-container/CHANGELOG.md) +- [google-cloud-containeranalysis==2.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-containeranalysis/CHANGELOG.md) +- [google-cloud-contentwarehouse==0.7.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contentwarehouse/CHANGELOG.md) +- [google-cloud-data-fusion==1.11.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-fusion/CHANGELOG.md) +- [google-cloud-data-qna==0.10.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-qna/CHANGELOG.md) +- [google-cloud-datacatalog-lineage==0.3.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog-lineage/CHANGELOG.md) +- [google-cloud-datacatalog==3.21.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog/CHANGELOG.md) +- [google-cloud-dataflow-client==0.8.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataflow-client/CHANGELOG.md) +- [google-cloud-dataform==0.5.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataform/CHANGELOG.md) +- [google-cloud-datalabeling==1.11.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datalabeling/CHANGELOG.md) +- [google-cloud-dataplex==2.3.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataplex/CHANGELOG.md) +- [google-cloud-dataproc-metastore==1.16.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc-metastore/CHANGELOG.md) +- [google-cloud-dataproc==5.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc/CHANGELOG.md) +- [google-cloud-datastream==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datastream/CHANGELOG.md) +- [google-cloud-deploy==2.2.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-deploy/CHANGELOG.md) +- [google-cloud-developerconnect==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-developerconnect/CHANGELOG.md) +- [google-cloud-dialogflow-cx==1.36.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow-cx/CHANGELOG.md) +- [google-cloud-dialogflow==2.34.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow/CHANGELOG.md) +- [google-cloud-discoveryengine==0.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-discoveryengine/CHANGELOG.md) +- [google-cloud-dlp==3.25.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dlp/CHANGELOG.md) +- [google-cloud-dms==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dms/CHANGELOG.md) +- [google-cloud-documentai==3.0.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-documentai/CHANGELOG.md) +- [google-cloud-domains==1.8.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-domains/CHANGELOG.md) +- [google-cloud-edgecontainer==0.5.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgecontainer/CHANGELOG.md) +- [google-cloud-edgenetwork==0.1.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgenetwork/CHANGELOG.md) +- [google-cloud-enterpriseknowledgegraph==0.3.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md) +- [google-cloud-essential-contacts==1.8.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-essential-contacts/CHANGELOG.md) +- [google-cloud-eventarc-publishing==0.6.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc-publishing/CHANGELOG.md) +- [google-cloud-eventarc==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc/CHANGELOG.md) +- [google-cloud-filestore==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-filestore/CHANGELOG.md) +- [google-cloud-functions==1.18.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-functions/CHANGELOG.md) +- [google-cloud-gdchardwaremanagement==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gdchardwaremanagement/CHANGELOG.md) +- [google-cloud-gke-backup==0.5.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-backup/CHANGELOG.md) +- [google-cloud-gke-connect-gateway==0.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-connect-gateway/CHANGELOG.md) +- [google-cloud-gke-hub==1.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-hub/CHANGELOG.md) +- [google-cloud-gke-multicloud==0.6.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-multicloud/CHANGELOG.md) +- [google-cloud-gsuiteaddons==0.3.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gsuiteaddons/CHANGELOG.md) +- [google-cloud-iam-logging==1.4.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam-logging/CHANGELOG.md) +- [google-cloud-iam==2.16.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam/CHANGELOG.md) +- [google-cloud-iap==1.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iap/CHANGELOG.md) +- [google-cloud-ids==1.8.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-ids/CHANGELOG.md) +- [google-cloud-kms-inventory==0.2.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms-inventory/CHANGELOG.md) +- [google-cloud-kms==3.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms/CHANGELOG.md) +- [google-cloud-language==2.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-language/CHANGELOG.md) +- [google-cloud-life-sciences==0.9.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-life-sciences/CHANGELOG.md) +- [google-cloud-managed-identities==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managed-identities/CHANGELOG.md) +- [google-cloud-managedkafka==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managedkafka/CHANGELOG.md) +- [google-cloud-media-translation==0.11.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-media-translation/CHANGELOG.md) +- [google-cloud-memcache==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-memcache/CHANGELOG.md) +- [google-cloud-migrationcenter==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-migrationcenter/CHANGELOG.md) +- [google-cloud-monitoring-dashboards==2.16.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-dashboards/CHANGELOG.md) +- [google-cloud-monitoring-metrics-scopes==1.7.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md) +- [google-cloud-monitoring==2.23.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring/CHANGELOG.md) +- [google-cloud-netapp==0.3.15](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-netapp/CHANGELOG.md) +- [google-cloud-network-connectivity==2.5.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-connectivity/CHANGELOG.md) +- [google-cloud-network-management==1.20.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management/CHANGELOG.md) +- [google-cloud-network-security==0.9.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security/CHANGELOG.md) +- [google-cloud-network-services==0.5.15](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-services/CHANGELOG.md) +- [google-cloud-notebooks==1.11.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-notebooks/CHANGELOG.md) +- [google-cloud-optimization==1.9.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-optimization/CHANGELOG.md) +- [google-cloud-oracledatabase==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-oracledatabase/CHANGELOG.md) +- [google-cloud-orchestration-airflow==1.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-orchestration-airflow/CHANGELOG.md) +- [google-cloud-os-config==1.18.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-config/CHANGELOG.md) +- [google-cloud-os-login==2.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-login/CHANGELOG.md) +- [google-cloud-parallelstore==0.2.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-parallelstore/CHANGELOG.md) +- [google-cloud-phishing-protection==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-phishing-protection/CHANGELOG.md) +- [google-cloud-policy-troubleshooter==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policy-troubleshooter/CHANGELOG.md) +- [google-cloud-policysimulator==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policysimulator/CHANGELOG.md) +- [google-cloud-policytroubleshooter-iam==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md) +- [google-cloud-private-ca==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-ca/CHANGELOG.md) +- [google-cloud-private-catalog==0.9.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-catalog/CHANGELOG.md) +- [google-cloud-privilegedaccessmanager==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-privilegedaccessmanager/CHANGELOG.md) +- [google-cloud-public-ca==0.3.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-public-ca/CHANGELOG.md) +- [google-cloud-quotas==0.1.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-quotas/CHANGELOG.md) +- [google-cloud-rapidmigrationassessment==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md) +- [google-cloud-recaptcha-enterprise==1.23.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md) +- [google-cloud-recommendations-ai==0.10.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommendations-ai/CHANGELOG.md) +- [google-cloud-recommender==2.16.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommender/CHANGELOG.md) +- [google-cloud-redis-cluster==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis-cluster/CHANGELOG.md) +- [google-cloud-redis==2.16.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis/CHANGELOG.md) +- [google-cloud-resource-manager==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-manager/CHANGELOG.md) +- [google-cloud-resource-settings==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-settings/CHANGELOG.md) +- [google-cloud-retail==1.23.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-retail/CHANGELOG.md) +- [google-cloud-run==0.10.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-run/CHANGELOG.md) +- [google-cloud-scheduler==2.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-scheduler/CHANGELOG.md) +- [google-cloud-secret-manager==2.21.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-secret-manager/CHANGELOG.md) +- [google-cloud-securesourcemanager==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securesourcemanager/CHANGELOG.md) +- [google-cloud-securitycenter==1.35.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter/CHANGELOG.md) +- [google-cloud-securitycentermanagement==0.1.15](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycentermanagement/CHANGELOG.md) +- [google-cloud-service-control==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-control/CHANGELOG.md) +- [google-cloud-service-directory==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-directory/CHANGELOG.md) +- [google-cloud-service-management==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-management/CHANGELOG.md) +- [google-cloud-service-usage==1.11.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-usage/CHANGELOG.md) +- [google-cloud-servicehealth==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-servicehealth/CHANGELOG.md) +- [google-cloud-shell==1.10.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-shell/CHANGELOG.md) +- [google-cloud-source-context==1.6.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-source-context/CHANGELOG.md) +- [google-cloud-speech==2.28.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-speech/CHANGELOG.md) +- [google-cloud-storage-control==1.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-control/CHANGELOG.md) +- [google-cloud-storage-transfer==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-transfer/CHANGELOG.md) +- [google-cloud-storageinsights==0.1.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storageinsights/CHANGELOG.md) +- [google-cloud-support==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-support/CHANGELOG.md) +- [google-cloud-talent==2.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-talent/CHANGELOG.md) +- [google-cloud-tasks==2.17.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tasks/CHANGELOG.md) +- [google-cloud-telcoautomation==0.2.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-telcoautomation/CHANGELOG.md) +- [google-cloud-texttospeech==2.20.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-texttospeech/CHANGELOG.md) +- [google-cloud-tpu==1.19.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tpu/CHANGELOG.md) +- [google-cloud-trace==1.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-trace/CHANGELOG.md) +- [google-cloud-translate==3.17.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-translate/CHANGELOG.md) +- [google-cloud-video-live-stream==1.9.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-live-stream/CHANGELOG.md) +- [google-cloud-video-stitcher==0.7.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-stitcher/CHANGELOG.md) +- [google-cloud-video-transcoder==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-transcoder/CHANGELOG.md) +- [google-cloud-videointelligence==2.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-videointelligence/CHANGELOG.md) +- [google-cloud-vision==3.8.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vision/CHANGELOG.md) +- [google-cloud-visionai==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-visionai/CHANGELOG.md) +- [google-cloud-vm-migration==1.9.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vm-migration/CHANGELOG.md) +- [google-cloud-vmwareengine==1.6.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vmwareengine/CHANGELOG.md) +- [google-cloud-vpc-access==1.11.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vpc-access/CHANGELOG.md) +- [google-cloud-webrisk==1.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-webrisk/CHANGELOG.md) +- [google-cloud-websecurityscanner==1.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-websecurityscanner/CHANGELOG.md) +- [google-cloud-workflows==1.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workflows/CHANGELOG.md) +- [google-cloud-workstations==0.5.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations/CHANGELOG.md) +- [google-geo-type==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-geo-type/CHANGELOG.md) +- [google-maps-addressvalidation==0.3.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-addressvalidation/CHANGELOG.md) +- [google-maps-areainsights==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-areainsights/CHANGELOG.md) +- [google-maps-fleetengine-delivery==0.2.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine-delivery/CHANGELOG.md) +- [google-maps-fleetengine==0.2.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine/CHANGELOG.md) +- [google-maps-mapsplatformdatasets==0.4.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-mapsplatformdatasets/CHANGELOG.md) +- [google-maps-places==0.1.19](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places/CHANGELOG.md) +- [google-maps-routeoptimization==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routeoptimization/CHANGELOG.md) +- [google-maps-routing==0.6.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routing/CHANGELOG.md) +- [google-maps-solar==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-solar/CHANGELOG.md) +- [google-shopping-css==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-css/CHANGELOG.md) +- [google-shopping-merchant-accounts==0.2.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-accounts/CHANGELOG.md) +- [google-shopping-merchant-conversions==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-conversions/CHANGELOG.md) +- [google-shopping-merchant-datasources==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-datasources/CHANGELOG.md) +- [google-shopping-merchant-inventories==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories/CHANGELOG.md) +- [google-shopping-merchant-lfp==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-lfp/CHANGELOG.md) +- [google-shopping-merchant-notifications==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-notifications/CHANGELOG.md) +- [google-shopping-merchant-products==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-products/CHANGELOG.md) +- [google-shopping-merchant-promotions==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-promotions/CHANGELOG.md) +- [google-shopping-merchant-quota==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-quota/CHANGELOG.md) +- [google-shopping-merchant-reports==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-reports/CHANGELOG.md) +- [google-shopping-type==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-type/CHANGELOG.md) +- [grafeas==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas/CHANGELOG.md) diff --git a/packages/google-ads-admanager/CHANGELOG.md b/packages/google-ads-admanager/CHANGELOG.md index 51bdcd8282ab..c117314d65f7 100644 --- a/packages/google-ads-admanager/CHANGELOG.md +++ b/packages/google-ads-admanager/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.2.2](https://github.com/googleapis/google-cloud-python/compare/google-ads-admanager-v0.2.1...google-ads-admanager-v0.2.2) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.2.1](https://github.com/googleapis/google-cloud-python/compare/google-ads-admanager-v0.2.0...google-ads-admanager-v0.2.1) (2024-10-24) diff --git a/packages/google-ads-admanager/google/ads/admanager/gapic_version.py b/packages/google-ads-admanager/google/ads/admanager/gapic_version.py index 6d8247638d59..d1a1a883babd 100644 --- a/packages/google-ads-admanager/google/ads/admanager/gapic_version.py +++ b/packages/google-ads-admanager/google/ads/admanager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.1" # {x-release-please-version} +__version__ = "0.2.2" # {x-release-please-version} diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_version.py b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_version.py index 6d8247638d59..d1a1a883babd 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_version.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.1" # {x-release-please-version} +__version__ = "0.2.2" # {x-release-please-version} diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_unit_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_unit_service/client.py index 3ba0ee87441f..c33e7ac32dd8 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_unit_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/ad_unit_service/client.py @@ -508,36 +508,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AdUnitServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -547,13 +517,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AdUnitServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/company_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/company_service/client.py index bb81bb301cfc..2af110bc0a6d 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/company_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/company_service/client.py @@ -531,36 +531,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CompanyServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -570,13 +540,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CompanyServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_field_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_field_service/client.py index 804dbce89b34..96798568f55a 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_field_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_field_service/client.py @@ -475,36 +475,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CustomFieldServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -514,13 +484,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CustomFieldServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_key_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_key_service/client.py index 0610955d547a..dcf8d11e56a6 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_key_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_key_service/client.py @@ -480,36 +480,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CustomTargetingKeyServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -519,13 +489,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CustomTargetingKeyServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/client.py index 062aecd5ee4f..d368fd9f95b7 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/custom_targeting_value_service/client.py @@ -489,36 +489,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CustomTargetingValueServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -528,13 +498,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CustomTargetingValueServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/entity_signals_mapping_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/entity_signals_mapping_service/client.py index dd85a50da159..072cd036e7f5 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/entity_signals_mapping_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/entity_signals_mapping_service/client.py @@ -480,36 +480,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = EntitySignalsMappingServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -519,13 +489,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or EntitySignalsMappingServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/client.py index 1d9ad0661c2d..6d6e51f15d37 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/client.py @@ -468,36 +468,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NetworkServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -507,13 +477,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NetworkServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/order_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/order_service/client.py index db1722c48eb7..3f8f3ca57f7f 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/order_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/order_service/client.py @@ -582,36 +582,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = OrderServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -621,13 +591,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or OrderServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/placement_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/placement_service/client.py index 05ef8cb3c56f..3c8735de6913 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/placement_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/placement_service/client.py @@ -493,36 +493,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PlacementServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -532,13 +502,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PlacementServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/report_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/report_service/client.py index 20d70845a1f4..5ccce8d9cf8a 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/report_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/report_service/client.py @@ -471,36 +471,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ReportServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -510,13 +480,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ReportServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/role_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/role_service/client.py index 41e0d8a8d012..12b4ded58fdd 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/role_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/role_service/client.py @@ -467,36 +467,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RoleServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -506,13 +476,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RoleServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/taxonomy_category_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/taxonomy_category_service/client.py index bd2882549d58..34d2eecbffc5 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/taxonomy_category_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/taxonomy_category_service/client.py @@ -478,36 +478,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TaxonomyCategoryServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -517,13 +487,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TaxonomyCategoryServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/user_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/user_service/client.py index 40bd220af88c..b8f7c7b12598 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/user_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/user_service/client.py @@ -468,36 +468,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = UserServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -507,13 +477,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or UserServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json b/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json index 054c7d9907ed..2480467d0962 100644 --- a/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json +++ b/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-ads-admanager", - "version": "0.2.1" + "version": "0.2.2" }, "snippets": [ { diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_ad_unit_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_ad_unit_service.py index 1b1919529a2d..8ad32e14d084 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_ad_unit_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_ad_unit_service.py @@ -316,85 +316,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AdUnitServiceClient, transports.AdUnitServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_company_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_company_service.py index 81a94d69c50c..31192a252ba0 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_company_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_company_service.py @@ -320,85 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CompanyServiceClient, transports.CompanyServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_field_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_field_service.py index 7e5bac6fc19a..8277a7391d0e 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_field_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_field_service.py @@ -330,85 +330,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CustomFieldServiceClient, transports.CustomFieldServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_targeting_key_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_targeting_key_service.py index 217824f3cc97..c638f5bc671f 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_targeting_key_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_targeting_key_service.py @@ -338,89 +338,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - CustomTargetingKeyServiceClient, - transports.CustomTargetingKeyServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_targeting_value_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_targeting_value_service.py index a9168197e4e1..3364cf5b4339 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_targeting_value_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_custom_targeting_value_service.py @@ -342,89 +342,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - CustomTargetingValueServiceClient, - transports.CustomTargetingValueServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_entity_signals_mapping_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_entity_signals_mapping_service.py index 744b2a57595e..6ac3e48f7132 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_entity_signals_mapping_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_entity_signals_mapping_service.py @@ -342,89 +342,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - EntitySignalsMappingServiceClient, - transports.EntitySignalsMappingServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_network_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_network_service.py index efbe6d4b9126..d81d1d2daacf 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_network_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_network_service.py @@ -312,85 +312,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (NetworkServiceClient, transports.NetworkServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_order_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_order_service.py index a9725a81786f..ff0845f7b8c7 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_order_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_order_service.py @@ -305,85 +305,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (OrderServiceClient, transports.OrderServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_placement_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_placement_service.py index 4cfcdf331f0c..e5ccc44d6400 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_placement_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_placement_service.py @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PlacementServiceClient, transports.PlacementServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_report_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_report_service.py index f4e6569c5321..de1573b91071 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_report_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_report_service.py @@ -323,85 +323,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ReportServiceClient, transports.ReportServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_role_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_role_service.py index 5e624b9b8992..a47b868d77ca 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_role_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_role_service.py @@ -294,85 +294,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RoleServiceClient, transports.RoleServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_taxonomy_category_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_taxonomy_category_service.py index a4c067ca6e81..c27e580f33f3 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_taxonomy_category_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_taxonomy_category_service.py @@ -334,89 +334,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - TaxonomyCategoryServiceClient, - transports.TaxonomyCategoryServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_user_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_user_service.py index d3f850d8228e..c90a6aafca07 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_user_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_user_service.py @@ -290,85 +290,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (UserServiceClient, transports.UserServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/CHANGELOG.md b/packages/google-ai-generativelanguage/CHANGELOG.md index 86db3cb6e4e5..19b681ab6681 100644 --- a/packages/google-ai-generativelanguage/CHANGELOG.md +++ b/packages/google-ai-generativelanguage/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.6.12](https://github.com/googleapis/google-cloud-python/compare/google-ai-generativelanguage-v0.6.11...google-ai-generativelanguage-v0.6.12) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.6.11](https://github.com/googleapis/google-cloud-python/compare/google-ai-generativelanguage-v0.6.10...google-ai-generativelanguage-v0.6.11) (2024-10-24) diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage/gapic_version.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage/gapic_version.py index 02b228845902..44e5c049e336 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage/gapic_version.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.11" # {x-release-please-version} +__version__ = "0.6.12" # {x-release-please-version} diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/gapic_version.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/gapic_version.py index 02b228845902..44e5c049e336 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/gapic_version.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.11" # {x-release-please-version} +__version__ = "0.6.12" # {x-release-please-version} diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/client.py index 8df3c91628d2..3194a369d1f6 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/client.py @@ -460,36 +460,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = GenerativeServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -499,13 +469,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or GenerativeServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/model_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/model_service/client.py index 5334e45117bc..18edd759c7e4 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/model_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/model_service/client.py @@ -456,36 +456,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ModelServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -495,13 +465,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ModelServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/gapic_version.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/gapic_version.py index 02b228845902..44e5c049e336 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/gapic_version.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.11" # {x-release-please-version} +__version__ = "0.6.12" # {x-release-please-version} diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/cache_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/cache_service/client.py index e5ce080ddfcb..1aa7d84159e5 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/cache_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/cache_service/client.py @@ -482,36 +482,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CacheServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -521,13 +491,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CacheServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/discuss_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/discuss_service/client.py index 3e8160f99d4d..656540db3a94 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/discuss_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/discuss_service/client.py @@ -459,36 +459,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DiscussServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -498,13 +468,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DiscussServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/file_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/file_service/client.py index 87de8e15bc6d..15732a3754a0 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/file_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/file_service/client.py @@ -456,36 +456,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = FileServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -495,13 +465,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or FileServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/client.py index 64141f79649a..ab10a4cf4406 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/client.py @@ -475,36 +475,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = GenerativeServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -514,13 +484,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or GenerativeServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/model_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/model_service/client.py index c35b6b3c2168..6bde8dc8aad9 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/model_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/model_service/client.py @@ -477,36 +477,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ModelServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -516,13 +486,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ModelServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/permission_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/permission_service/client.py index 61db870f8cb2..fa1ec2eb1fc8 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/permission_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/permission_service/client.py @@ -465,36 +465,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PermissionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -504,13 +474,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PermissionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/prediction_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/prediction_service/client.py index 48736239098d..2feee7d907b6 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/prediction_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/prediction_service/client.py @@ -456,36 +456,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PredictionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -495,13 +465,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PredictionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/retriever_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/retriever_service/client.py index 2efc8f181dd1..ba7e81a48515 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/retriever_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/retriever_service/client.py @@ -499,36 +499,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RetrieverServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -538,13 +508,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RetrieverServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/text_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/text_service/client.py index 37c0ff946c1e..1cb5aa54494e 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/text_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/text_service/client.py @@ -457,36 +457,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TextServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -496,13 +466,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TextServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/gapic_version.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/gapic_version.py index 02b228845902..44e5c049e336 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/gapic_version.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.11" # {x-release-please-version} +__version__ = "0.6.12" # {x-release-please-version} diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/discuss_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/discuss_service/client.py index 18bbc6108ddd..76d71583a294 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/discuss_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/discuss_service/client.py @@ -457,36 +457,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DiscussServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -496,13 +466,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DiscussServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/model_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/model_service/client.py index b4c965681988..ded53d4a1793 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/model_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/model_service/client.py @@ -454,36 +454,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ModelServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -493,13 +463,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ModelServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/text_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/text_service/client.py index 74a4d9424c53..9663add6a459 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/text_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta2/services/text_service/client.py @@ -455,36 +455,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TextServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -494,13 +464,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TextServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/gapic_version.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/gapic_version.py index 02b228845902..44e5c049e336 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/gapic_version.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.11" # {x-release-please-version} +__version__ = "0.6.12" # {x-release-please-version} diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/discuss_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/discuss_service/client.py index 3f96ccafb73a..9c0f32e7be0a 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/discuss_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/discuss_service/client.py @@ -459,36 +459,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DiscussServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -498,13 +468,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DiscussServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/model_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/model_service/client.py index f76ac868c667..3e4196c6d5d8 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/model_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/model_service/client.py @@ -477,36 +477,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ModelServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -516,13 +486,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ModelServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/permission_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/permission_service/client.py index fbbd86c3e7d5..6d126b1d3c03 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/permission_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/permission_service/client.py @@ -480,36 +480,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PermissionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -519,13 +489,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PermissionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/text_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/text_service/client.py index ad257c9d2909..a9ca258b4b31 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/text_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta3/services/text_service/client.py @@ -457,36 +457,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TextServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -496,13 +466,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TextServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1.json b/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1.json index 2a3900f7d9fc..8a2a6c91e868 100644 --- a/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1.json +++ b/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-ai-generativelanguage", - "version": "0.6.11" + "version": "0.6.12" }, "snippets": [ { diff --git a/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta.json b/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta.json index 92c04dafd1ea..9ec94c204cf3 100644 --- a/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta.json +++ b/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-ai-generativelanguage", - "version": "0.6.11" + "version": "0.6.12" }, "snippets": [ { diff --git a/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta2.json b/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta2.json index bf9329fcee8f..33ea36110ba5 100644 --- a/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta2.json +++ b/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-ai-generativelanguage", - "version": "0.6.11" + "version": "0.6.12" }, "snippets": [ { diff --git a/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta3.json b/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta3.json index 88a39493c282..e75232ce026a 100644 --- a/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta3.json +++ b/packages/google-ai-generativelanguage/samples/generated_samples/snippet_metadata_google.ai.generativelanguage.v1beta3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-ai-generativelanguage", - "version": "0.6.11" + "version": "0.6.12" }, "snippets": [ { diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1/test_generative_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1/test_generative_service.py index 715f4b18c201..52ce2d8fb7da 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1/test_generative_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1/test_generative_service.py @@ -329,86 +329,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (GenerativeServiceClient, transports.GenerativeServiceGrpcTransport, "grpc"), - (GenerativeServiceClient, transports.GenerativeServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1/test_model_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1/test_model_service.py index 15b7aa9d348c..4321e032b0e9 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1/test_model_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1/test_model_service.py @@ -304,86 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ModelServiceClient, transports.ModelServiceGrpcTransport, "grpc"), - (ModelServiceClient, transports.ModelServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_cache_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_cache_service.py index 4da54c2f1ed1..aaf5e8c0a8ef 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_cache_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_cache_service.py @@ -313,86 +313,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CacheServiceClient, transports.CacheServiceGrpcTransport, "grpc"), - (CacheServiceClient, transports.CacheServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_discuss_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_discuss_service.py index 5700d8058173..5a22f6fbbf77 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_discuss_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_discuss_service.py @@ -318,86 +318,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DiscussServiceClient, transports.DiscussServiceGrpcTransport, "grpc"), - (DiscussServiceClient, transports.DiscussServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_file_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_file_service.py index 4137b47b47c9..fb860e96f676 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_file_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_file_service.py @@ -304,86 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (FileServiceClient, transports.FileServiceGrpcTransport, "grpc"), - (FileServiceClient, transports.FileServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_generative_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_generative_service.py index b2464bad5159..e5be0ab99b6d 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_generative_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_generative_service.py @@ -334,86 +334,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (GenerativeServiceClient, transports.GenerativeServiceGrpcTransport, "grpc"), - (GenerativeServiceClient, transports.GenerativeServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_model_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_model_service.py index fadad45162ed..281420e86a16 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_model_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_model_service.py @@ -317,86 +317,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ModelServiceClient, transports.ModelServiceGrpcTransport, "grpc"), - (ModelServiceClient, transports.ModelServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_permission_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_permission_service.py index 6940cf61ff48..abb7d4b5b287 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_permission_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_permission_service.py @@ -331,86 +331,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PermissionServiceClient, transports.PermissionServiceGrpcTransport, "grpc"), - (PermissionServiceClient, transports.PermissionServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_prediction_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_prediction_service.py index 2553c659f7a1..38d84a9a2b8d 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_prediction_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_prediction_service.py @@ -328,86 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceClient, transports.PredictionServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_retriever_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_retriever_service.py index 1a5cf0f47db9..4ba6216c3c8c 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_retriever_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_retriever_service.py @@ -322,86 +322,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RetrieverServiceClient, transports.RetrieverServiceGrpcTransport, "grpc"), - (RetrieverServiceClient, transports.RetrieverServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_text_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_text_service.py index 0d4dd8f9b886..0c848a4d1a6e 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_text_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_text_service.py @@ -299,86 +299,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TextServiceClient, transports.TextServiceGrpcTransport, "grpc"), - (TextServiceClient, transports.TextServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_discuss_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_discuss_service.py index ea09837f70b5..6745f00aecb3 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_discuss_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_discuss_service.py @@ -317,86 +317,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DiscussServiceClient, transports.DiscussServiceGrpcTransport, "grpc"), - (DiscussServiceClient, transports.DiscussServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_model_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_model_service.py index 5a343846e529..eac582efe3d0 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_model_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_model_service.py @@ -303,86 +303,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ModelServiceClient, transports.ModelServiceGrpcTransport, "grpc"), - (ModelServiceClient, transports.ModelServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_text_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_text_service.py index eb6bcfec2536..5dce1f43b446 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_text_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta2/test_text_service.py @@ -298,86 +298,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TextServiceClient, transports.TextServiceGrpcTransport, "grpc"), - (TextServiceClient, transports.TextServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_discuss_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_discuss_service.py index bfd0a465e928..0440cb22380c 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_discuss_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_discuss_service.py @@ -318,86 +318,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DiscussServiceClient, transports.DiscussServiceGrpcTransport, "grpc"), - (DiscussServiceClient, transports.DiscussServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_model_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_model_service.py index d0e31fb13ffe..8247ca3c9236 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_model_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_model_service.py @@ -317,86 +317,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ModelServiceClient, transports.ModelServiceGrpcTransport, "grpc"), - (ModelServiceClient, transports.ModelServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_permission_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_permission_service.py index dd7ce80bfffb..749dd92ab0b7 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_permission_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_permission_service.py @@ -331,86 +331,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PermissionServiceClient, transports.PermissionServiceGrpcTransport, "grpc"), - (PermissionServiceClient, transports.PermissionServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_text_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_text_service.py index cf452f7e5433..f5fda3b37e0b 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_text_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta3/test_text_service.py @@ -299,86 +299,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TextServiceClient, transports.TextServiceGrpcTransport, "grpc"), - (TextServiceClient, transports.TextServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-analytics-admin/CHANGELOG.md b/packages/google-analytics-admin/CHANGELOG.md index 280a75f58ba5..d0a27b83e4bf 100644 --- a/packages/google-analytics-admin/CHANGELOG.md +++ b/packages/google-analytics-admin/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.23.2](https://github.com/googleapis/google-cloud-python/compare/google-analytics-admin-v0.23.1...google-analytics-admin-v0.23.2) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.23.1](https://github.com/googleapis/google-cloud-python/compare/google-analytics-admin-v0.23.0...google-analytics-admin-v0.23.1) (2024-10-24) diff --git a/packages/google-analytics-admin/google/analytics/admin/gapic_version.py b/packages/google-analytics-admin/google/analytics/admin/gapic_version.py index a63d749c3969..ea568fc1a5a7 100644 --- a/packages/google-analytics-admin/google/analytics/admin/gapic_version.py +++ b/packages/google-analytics-admin/google/analytics/admin/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.23.1" # {x-release-please-version} +__version__ = "0.23.2" # {x-release-please-version} diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_version.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_version.py index a63d749c3969..ea568fc1a5a7 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_version.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.23.1" # {x-release-please-version} +__version__ = "0.23.2" # {x-release-please-version} diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py index 5ac6b7f05edf..bfc42cfdb936 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py @@ -1100,36 +1100,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -1139,13 +1109,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AnalyticsAdminServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-analytics-admin/google/analytics/admin_v1beta/gapic_version.py b/packages/google-analytics-admin/google/analytics/admin_v1beta/gapic_version.py index a63d749c3969..ea568fc1a5a7 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1beta/gapic_version.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.23.1" # {x-release-please-version} +__version__ = "0.23.2" # {x-release-please-version} diff --git a/packages/google-analytics-admin/google/analytics/admin_v1beta/services/analytics_admin_service/client.py b/packages/google-analytics-admin/google/analytics/admin_v1beta/services/analytics_admin_service/client.py index baf4b1ed050c..990b9511e610 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1beta/services/analytics_admin_service/client.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1beta/services/analytics_admin_service/client.py @@ -697,36 +697,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -736,13 +706,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AnalyticsAdminServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-analytics-admin/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json b/packages/google-analytics-admin/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json index bfb7e2f7c846..5141448d6c81 100644 --- a/packages/google-analytics-admin/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json +++ b/packages/google-analytics-admin/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-analytics-admin", - "version": "0.23.1" + "version": "0.23.2" }, "snippets": [ { diff --git a/packages/google-analytics-admin/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py b/packages/google-analytics-admin/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py index 622f53317f23..881d7f07eeda 100644 --- a/packages/google-analytics-admin/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py +++ b/packages/google-analytics-admin/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py @@ -353,94 +353,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AnalyticsAdminServiceClient, - transports.AnalyticsAdminServiceGrpcTransport, - "grpc", - ), - ( - AnalyticsAdminServiceClient, - transports.AnalyticsAdminServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-analytics-admin/tests/unit/gapic/admin_v1beta/test_analytics_admin_service.py b/packages/google-analytics-admin/tests/unit/gapic/admin_v1beta/test_analytics_admin_service.py index 9919c341e9f4..9b5864916859 100644 --- a/packages/google-analytics-admin/tests/unit/gapic/admin_v1beta/test_analytics_admin_service.py +++ b/packages/google-analytics-admin/tests/unit/gapic/admin_v1beta/test_analytics_admin_service.py @@ -342,94 +342,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AnalyticsAdminServiceClient, - transports.AnalyticsAdminServiceGrpcTransport, - "grpc", - ), - ( - AnalyticsAdminServiceClient, - transports.AnalyticsAdminServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-analytics-data/CHANGELOG.md b/packages/google-analytics-data/CHANGELOG.md index 0f3b7524c13c..a4e2a9305477 100644 --- a/packages/google-analytics-data/CHANGELOG.md +++ b/packages/google-analytics-data/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.18.15](https://github.com/googleapis/google-cloud-python/compare/google-analytics-data-v0.18.14...google-analytics-data-v0.18.15) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.18.14](https://github.com/googleapis/google-cloud-python/compare/google-analytics-data-v0.18.13...google-analytics-data-v0.18.14) (2024-10-24) diff --git a/packages/google-analytics-data/google/analytics/data/gapic_version.py b/packages/google-analytics-data/google/analytics/data/gapic_version.py index e99a91f4ef5b..f9d274b1cc84 100644 --- a/packages/google-analytics-data/google/analytics/data/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.18.14" # {x-release-please-version} +__version__ = "0.18.15" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py b/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py index e99a91f4ef5b..f9d274b1cc84 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.18.14" # {x-release-please-version} +__version__ = "0.18.15" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py index 2b333ae4af4a..4911b5cf8c7e 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py @@ -517,36 +517,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AlphaAnalyticsDataClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -556,13 +526,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AlphaAnalyticsDataClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py b/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py index e99a91f4ef5b..f9d274b1cc84 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.18.14" # {x-release-please-version} +__version__ = "0.18.15" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/services/beta_analytics_data/client.py b/packages/google-analytics-data/google/analytics/data_v1beta/services/beta_analytics_data/client.py index 0e5f00491f32..1ab80c89ab8b 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/services/beta_analytics_data/client.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/services/beta_analytics_data/client.py @@ -479,36 +479,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BetaAnalyticsDataClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -518,13 +488,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BetaAnalyticsDataClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json index 91daeaf79a0e..0366b1d9f8a8 100644 --- a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json +++ b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-analytics-data", - "version": "0.18.14" + "version": "0.18.15" }, "snippets": [ { diff --git a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json index 4fd8e98c09ba..b65d9d8958c0 100644 --- a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json +++ b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-analytics-data", - "version": "0.18.14" + "version": "0.18.15" }, "snippets": [ { diff --git a/packages/google-analytics-data/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py b/packages/google-analytics-data/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py index 39b4b1e0362f..c349785c674b 100644 --- a/packages/google-analytics-data/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py +++ b/packages/google-analytics-data/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py @@ -343,86 +343,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataGrpcTransport, "grpc"), - (AlphaAnalyticsDataClient, transports.AlphaAnalyticsDataRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-analytics-data/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py b/packages/google-analytics-data/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py index 500148343b0b..c32d40baa2b6 100644 --- a/packages/google-analytics-data/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py +++ b/packages/google-analytics-data/tests/unit/gapic/data_v1beta/test_beta_analytics_data.py @@ -338,86 +338,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataGrpcTransport, "grpc"), - (BetaAnalyticsDataClient, transports.BetaAnalyticsDataRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-apps-chat/CHANGELOG.md b/packages/google-apps-chat/CHANGELOG.md index b88b195d48a9..7e8bf5b321a0 100644 --- a/packages/google-apps-chat/CHANGELOG.md +++ b/packages/google-apps-chat/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.14](https://github.com/googleapis/google-cloud-python/compare/google-apps-chat-v0.1.13...google-apps-chat-v0.1.14) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.1.13](https://github.com/googleapis/google-cloud-python/compare/google-apps-chat-v0.1.12...google-apps-chat-v0.1.13) (2024-10-24) diff --git a/packages/google-apps-chat/google/apps/chat/gapic_version.py b/packages/google-apps-chat/google/apps/chat/gapic_version.py index 7daf9a1dd221..7a4d810a47da 100644 --- a/packages/google-apps-chat/google/apps/chat/gapic_version.py +++ b/packages/google-apps-chat/google/apps/chat/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.13" # {x-release-please-version} +__version__ = "0.1.14" # {x-release-please-version} diff --git a/packages/google-apps-chat/google/apps/chat_v1/gapic_version.py b/packages/google-apps-chat/google/apps/chat_v1/gapic_version.py index 7daf9a1dd221..7a4d810a47da 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/gapic_version.py +++ b/packages/google-apps-chat/google/apps/chat_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.13" # {x-release-please-version} +__version__ = "0.1.14" # {x-release-please-version} diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py index 54e871750f4b..f38740dd5526 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py @@ -654,36 +654,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ChatServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -693,13 +663,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ChatServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json b/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json index 8cf1ba757e75..b4693d56a9b2 100644 --- a/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json +++ b/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-apps-chat", - "version": "0.1.13" + "version": "0.1.14" }, "snippets": [ { diff --git a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py index 3115a124f161..b5c828d4d20d 100644 --- a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py +++ b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py @@ -328,86 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc"), - (ChatServiceClient, transports.ChatServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-apps-events-subscriptions/CHANGELOG.md b/packages/google-apps-events-subscriptions/CHANGELOG.md index 37420dec6b4c..69548d98ca25 100644 --- a/packages/google-apps-events-subscriptions/CHANGELOG.md +++ b/packages/google-apps-events-subscriptions/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-apps-events-subscriptions-v0.1.3...google-apps-events-subscriptions-v0.1.4) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.1.3](https://github.com/googleapis/google-cloud-python/compare/google-apps-events-subscriptions-v0.1.2...google-apps-events-subscriptions-v0.1.3) (2024-10-24) diff --git a/packages/google-apps-events-subscriptions/events-subscriptions-v1-py.tar.gz b/packages/google-apps-events-subscriptions/events-subscriptions-v1-py.tar.gz new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/packages/google-apps-events-subscriptions/google/apps/events_subscriptions/gapic_version.py b/packages/google-apps-events-subscriptions/google/apps/events_subscriptions/gapic_version.py index 114e40645800..937ede8823ef 100644 --- a/packages/google-apps-events-subscriptions/google/apps/events_subscriptions/gapic_version.py +++ b/packages/google-apps-events-subscriptions/google/apps/events_subscriptions/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.3" # {x-release-please-version} +__version__ = "0.1.4" # {x-release-please-version} diff --git a/packages/google-apps-events-subscriptions/google/apps/events_subscriptions_v1/gapic_version.py b/packages/google-apps-events-subscriptions/google/apps/events_subscriptions_v1/gapic_version.py index 114e40645800..937ede8823ef 100644 --- a/packages/google-apps-events-subscriptions/google/apps/events_subscriptions_v1/gapic_version.py +++ b/packages/google-apps-events-subscriptions/google/apps/events_subscriptions_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.3" # {x-release-please-version} +__version__ = "0.1.4" # {x-release-please-version} diff --git a/packages/google-apps-events-subscriptions/google/apps/events_subscriptions_v1/services/subscriptions_service/client.py b/packages/google-apps-events-subscriptions/google/apps/events_subscriptions_v1/services/subscriptions_service/client.py index 9059b3361f64..44bd27225c06 100644 --- a/packages/google-apps-events-subscriptions/google/apps/events_subscriptions_v1/services/subscriptions_service/client.py +++ b/packages/google-apps-events-subscriptions/google/apps/events_subscriptions_v1/services/subscriptions_service/client.py @@ -499,36 +499,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SubscriptionsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -538,13 +508,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SubscriptionsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-apps-events-subscriptions/samples/generated_samples/snippet_metadata_google.apps.events.subscriptions.v1.json b/packages/google-apps-events-subscriptions/samples/generated_samples/snippet_metadata_google.apps.events.subscriptions.v1.json index 1a915cd4960a..3d32acd71a3d 100644 --- a/packages/google-apps-events-subscriptions/samples/generated_samples/snippet_metadata_google.apps.events.subscriptions.v1.json +++ b/packages/google-apps-events-subscriptions/samples/generated_samples/snippet_metadata_google.apps.events.subscriptions.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-apps-events-subscriptions", - "version": "0.1.3" + "version": "0.1.4" }, "snippets": [ { diff --git a/packages/google-apps-events-subscriptions/tests/unit/gapic/events_subscriptions_v1/test_subscriptions_service.py b/packages/google-apps-events-subscriptions/tests/unit/gapic/events_subscriptions_v1/test_subscriptions_service.py index a4ffe34c1ba0..d1ea54d0926c 100644 --- a/packages/google-apps-events-subscriptions/tests/unit/gapic/events_subscriptions_v1/test_subscriptions_service.py +++ b/packages/google-apps-events-subscriptions/tests/unit/gapic/events_subscriptions_v1/test_subscriptions_service.py @@ -350,94 +350,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - SubscriptionsServiceClient, - transports.SubscriptionsServiceGrpcTransport, - "grpc", - ), - ( - SubscriptionsServiceClient, - transports.SubscriptionsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-apps-meet/CHANGELOG.md b/packages/google-apps-meet/CHANGELOG.md index 436c26e7100d..d6d442ccb40e 100644 --- a/packages/google-apps-meet/CHANGELOG.md +++ b/packages/google-apps-meet/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.10](https://github.com/googleapis/google-cloud-python/compare/google-apps-meet-v0.1.9...google-apps-meet-v0.1.10) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.1.9](https://github.com/googleapis/google-cloud-python/compare/google-apps-meet-v0.1.8...google-apps-meet-v0.1.9) (2024-10-24) diff --git a/packages/google-apps-meet/google/apps/meet/gapic_version.py b/packages/google-apps-meet/google/apps/meet/gapic_version.py index f8ea948a9c30..9413c3341313 100644 --- a/packages/google-apps-meet/google/apps/meet/gapic_version.py +++ b/packages/google-apps-meet/google/apps/meet/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.9" # {x-release-please-version} +__version__ = "0.1.10" # {x-release-please-version} diff --git a/packages/google-apps-meet/google/apps/meet_v2/gapic_version.py b/packages/google-apps-meet/google/apps/meet_v2/gapic_version.py index f8ea948a9c30..9413c3341313 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/gapic_version.py +++ b/packages/google-apps-meet/google/apps/meet_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.9" # {x-release-please-version} +__version__ = "0.1.10" # {x-release-please-version} diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/client.py b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/client.py index 4001fe724b57..55f1e5855eab 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/client.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/conference_records_service/client.py @@ -579,36 +579,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConferenceRecordsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -618,13 +588,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ConferenceRecordsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/client.py b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/client.py index 7a6bed8a44d2..707bba6f8b1f 100644 --- a/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/client.py +++ b/packages/google-apps-meet/google/apps/meet_v2/services/spaces_service/client.py @@ -468,36 +468,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SpacesServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -507,13 +477,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SpacesServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/gapic_version.py b/packages/google-apps-meet/google/apps/meet_v2beta/gapic_version.py index f8ea948a9c30..9413c3341313 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/gapic_version.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.9" # {x-release-please-version} +__version__ = "0.1.10" # {x-release-please-version} diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/client.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/client.py index 4764e9d20ae9..05b4fac29dda 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/client.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/conference_records_service/client.py @@ -579,36 +579,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConferenceRecordsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -618,13 +588,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ConferenceRecordsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/client.py b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/client.py index a8c4f208485c..4280b547792d 100644 --- a/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/client.py +++ b/packages/google-apps-meet/google/apps/meet_v2beta/services/spaces_service/client.py @@ -468,36 +468,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SpacesServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -507,13 +477,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SpacesServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2.json b/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2.json index a0252a24c186..7c2d00f3bd03 100644 --- a/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2.json +++ b/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-apps-meet", - "version": "0.1.9" + "version": "0.1.10" }, "snippets": [ { diff --git a/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2beta.json b/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2beta.json index f080ac6e008d..035063797335 100644 --- a/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2beta.json +++ b/packages/google-apps-meet/samples/generated_samples/snippet_metadata_google.apps.meet.v2beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-apps-meet", - "version": "0.1.9" + "version": "0.1.10" }, "snippets": [ { diff --git a/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_conference_records_service.py b/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_conference_records_service.py index 88328e89b302..3a6c0733060e 100644 --- a/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_conference_records_service.py +++ b/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_conference_records_service.py @@ -336,94 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ConferenceRecordsServiceClient, - transports.ConferenceRecordsServiceGrpcTransport, - "grpc", - ), - ( - ConferenceRecordsServiceClient, - transports.ConferenceRecordsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_spaces_service.py b/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_spaces_service.py index cc8817eb4937..d9e07ca663a9 100644 --- a/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_spaces_service.py +++ b/packages/google-apps-meet/tests/unit/gapic/meet_v2/test_spaces_service.py @@ -314,86 +314,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SpacesServiceClient, transports.SpacesServiceGrpcTransport, "grpc"), - (SpacesServiceClient, transports.SpacesServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_conference_records_service.py b/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_conference_records_service.py index b95f8ee88f79..d6473b5f7155 100644 --- a/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_conference_records_service.py +++ b/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_conference_records_service.py @@ -336,94 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ConferenceRecordsServiceClient, - transports.ConferenceRecordsServiceGrpcTransport, - "grpc", - ), - ( - ConferenceRecordsServiceClient, - transports.ConferenceRecordsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_spaces_service.py b/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_spaces_service.py index 1493ba93b11c..810e4251778b 100644 --- a/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_spaces_service.py +++ b/packages/google-apps-meet/tests/unit/gapic/meet_v2beta/test_spaces_service.py @@ -314,86 +314,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SpacesServiceClient, transports.SpacesServiceGrpcTransport, "grpc"), - (SpacesServiceClient, transports.SpacesServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-area120-tables/CHANGELOG.md b/packages/google-area120-tables/CHANGELOG.md index 6b482237128d..fdbb14de13b7 100644 --- a/packages/google-area120-tables/CHANGELOG.md +++ b/packages/google-area120-tables/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.11.13](https://github.com/googleapis/google-cloud-python/compare/google-area120-tables-v0.11.12...google-area120-tables-v0.11.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.11.12](https://github.com/googleapis/google-cloud-python/compare/google-area120-tables-v0.11.11...google-area120-tables-v0.11.12) (2024-10-24) diff --git a/packages/google-area120-tables/google/area120/tables/gapic_version.py b/packages/google-area120-tables/google/area120/tables/gapic_version.py index 2566b8be8361..082d8f13abe1 100644 --- a/packages/google-area120-tables/google/area120/tables/gapic_version.py +++ b/packages/google-area120-tables/google/area120/tables/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.12" # {x-release-please-version} +__version__ = "0.11.13" # {x-release-please-version} diff --git a/packages/google-area120-tables/google/area120/tables_v1alpha1/gapic_version.py b/packages/google-area120-tables/google/area120/tables_v1alpha1/gapic_version.py index 2566b8be8361..082d8f13abe1 100644 --- a/packages/google-area120-tables/google/area120/tables_v1alpha1/gapic_version.py +++ b/packages/google-area120-tables/google/area120/tables_v1alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.12" # {x-release-please-version} +__version__ = "0.11.13" # {x-release-please-version} diff --git a/packages/google-area120-tables/google/area120/tables_v1alpha1/services/tables_service/client.py b/packages/google-area120-tables/google/area120/tables_v1alpha1/services/tables_service/client.py index 871e6857384e..3da7cb1d546b 100644 --- a/packages/google-area120-tables/google/area120/tables_v1alpha1/services/tables_service/client.py +++ b/packages/google-area120-tables/google/area120/tables_v1alpha1/services/tables_service/client.py @@ -500,36 +500,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TablesServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -539,13 +509,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TablesServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-area120-tables/samples/generated_samples/snippet_metadata_google.area120.tables.v1alpha1.json b/packages/google-area120-tables/samples/generated_samples/snippet_metadata_google.area120.tables.v1alpha1.json index 7f849d31c21e..a436ed8a890c 100644 --- a/packages/google-area120-tables/samples/generated_samples/snippet_metadata_google.area120.tables.v1alpha1.json +++ b/packages/google-area120-tables/samples/generated_samples/snippet_metadata_google.area120.tables.v1alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-area120-tables", - "version": "0.11.12" + "version": "0.11.13" }, "snippets": [ { diff --git a/packages/google-area120-tables/tests/unit/gapic/tables_v1alpha1/test_tables_service.py b/packages/google-area120-tables/tests/unit/gapic/tables_v1alpha1/test_tables_service.py index 4f0221b25d68..d1015f86f246 100644 --- a/packages/google-area120-tables/tests/unit/gapic/tables_v1alpha1/test_tables_service.py +++ b/packages/google-area120-tables/tests/unit/gapic/tables_v1alpha1/test_tables_service.py @@ -316,86 +316,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TablesServiceClient, transports.TablesServiceGrpcTransport, "grpc"), - (TablesServiceClient, transports.TablesServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-access-approval/CHANGELOG.md b/packages/google-cloud-access-approval/CHANGELOG.md index 1bbd3c69cb10..bc1996c7e54d 100644 --- a/packages/google-cloud-access-approval/CHANGELOG.md +++ b/packages/google-cloud-access-approval/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.14.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-access-approval-v1.14.0...google-cloud-access-approval-v1.14.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [1.14.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-access-approval-v1.13.5...google-cloud-access-approval-v1.14.0) (2024-10-24) diff --git a/packages/google-cloud-access-approval/google/cloud/accessapproval/gapic_version.py b/packages/google-cloud-access-approval/google/cloud/accessapproval/gapic_version.py index 2159c8af6f8e..231f5cf041ff 100644 --- a/packages/google-cloud-access-approval/google/cloud/accessapproval/gapic_version.py +++ b/packages/google-cloud-access-approval/google/cloud/accessapproval/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.0" # {x-release-please-version} +__version__ = "1.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-access-approval/google/cloud/accessapproval_v1/gapic_version.py b/packages/google-cloud-access-approval/google/cloud/accessapproval_v1/gapic_version.py index 2159c8af6f8e..231f5cf041ff 100644 --- a/packages/google-cloud-access-approval/google/cloud/accessapproval_v1/gapic_version.py +++ b/packages/google-cloud-access-approval/google/cloud/accessapproval_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.0" # {x-release-please-version} +__version__ = "1.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-access-approval/google/cloud/accessapproval_v1/services/access_approval/client.py b/packages/google-cloud-access-approval/google/cloud/accessapproval_v1/services/access_approval/client.py index 3a134b51689f..73acca6528d2 100644 --- a/packages/google-cloud-access-approval/google/cloud/accessapproval_v1/services/access_approval/client.py +++ b/packages/google-cloud-access-approval/google/cloud/accessapproval_v1/services/access_approval/client.py @@ -527,36 +527,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AccessApprovalClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -566,13 +536,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AccessApprovalClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-access-approval/samples/generated_samples/snippet_metadata_google.cloud.accessapproval.v1.json b/packages/google-cloud-access-approval/samples/generated_samples/snippet_metadata_google.cloud.accessapproval.v1.json index cacb025281c3..2daa4d5daa12 100644 --- a/packages/google-cloud-access-approval/samples/generated_samples/snippet_metadata_google.cloud.accessapproval.v1.json +++ b/packages/google-cloud-access-approval/samples/generated_samples/snippet_metadata_google.cloud.accessapproval.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-access-approval", - "version": "1.14.0" + "version": "1.14.1" }, "snippets": [ { diff --git a/packages/google-cloud-access-approval/tests/unit/gapic/accessapproval_v1/test_access_approval.py b/packages/google-cloud-access-approval/tests/unit/gapic/accessapproval_v1/test_access_approval.py index 9879fc9e98e7..47aabbb3b84e 100644 --- a/packages/google-cloud-access-approval/tests/unit/gapic/accessapproval_v1/test_access_approval.py +++ b/packages/google-cloud-access-approval/tests/unit/gapic/accessapproval_v1/test_access_approval.py @@ -320,86 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AccessApprovalClient, transports.AccessApprovalGrpcTransport, "grpc"), - (AccessApprovalClient, transports.AccessApprovalRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-advisorynotifications/CHANGELOG.md b/packages/google-cloud-advisorynotifications/CHANGELOG.md index 9ad74ede8fa7..3110e03f654c 100644 --- a/packages/google-cloud-advisorynotifications/CHANGELOG.md +++ b/packages/google-cloud-advisorynotifications/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-advisorynotifications-v0.3.11...google-cloud-advisorynotifications-v0.3.12) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.3.11](https://github.com/googleapis/google-cloud-python/compare/google-cloud-advisorynotifications-v0.3.10...google-cloud-advisorynotifications-v0.3.11) (2024-10-24) diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/gapic_version.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/gapic_version.py index 075108786e34..ab68833be4be 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/gapic_version.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.11" # {x-release-please-version} +__version__ = "0.3.12" # {x-release-please-version} diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_version.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_version.py index 075108786e34..ab68833be4be 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_version.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.11" # {x-release-please-version} +__version__ = "0.3.12" # {x-release-please-version} diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/client.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/client.py index 1596808d73f2..9c15dcb41216 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/client.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/client.py @@ -491,36 +491,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AdvisoryNotificationsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -530,13 +500,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AdvisoryNotificationsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-advisorynotifications/samples/generated_samples/snippet_metadata_google.cloud.advisorynotifications.v1.json b/packages/google-cloud-advisorynotifications/samples/generated_samples/snippet_metadata_google.cloud.advisorynotifications.v1.json index 932eb864b320..ef66fef02aae 100644 --- a/packages/google-cloud-advisorynotifications/samples/generated_samples/snippet_metadata_google.cloud.advisorynotifications.v1.json +++ b/packages/google-cloud-advisorynotifications/samples/generated_samples/snippet_metadata_google.cloud.advisorynotifications.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-advisorynotifications", - "version": "0.3.11" + "version": "0.3.12" }, "snippets": [ { diff --git a/packages/google-cloud-advisorynotifications/tests/unit/gapic/advisorynotifications_v1/test_advisory_notifications_service.py b/packages/google-cloud-advisorynotifications/tests/unit/gapic/advisorynotifications_v1/test_advisory_notifications_service.py index c581d5978383..d86d398f7521 100644 --- a/packages/google-cloud-advisorynotifications/tests/unit/gapic/advisorynotifications_v1/test_advisory_notifications_service.py +++ b/packages/google-cloud-advisorynotifications/tests/unit/gapic/advisorynotifications_v1/test_advisory_notifications_service.py @@ -346,94 +346,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AdvisoryNotificationsServiceClient, - transports.AdvisoryNotificationsServiceGrpcTransport, - "grpc", - ), - ( - AdvisoryNotificationsServiceClient, - transports.AdvisoryNotificationsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-alloydb/CHANGELOG.md b/packages/google-cloud-alloydb/CHANGELOG.md index 8ceb68d9bc24..82c07d18f73f 100644 --- a/packages/google-cloud-alloydb/CHANGELOG.md +++ b/packages/google-cloud-alloydb/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.16](https://github.com/googleapis/google-cloud-python/compare/google-cloud-alloydb-v0.3.15...google-cloud-alloydb-v0.3.16) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.3.15](https://github.com/googleapis/google-cloud-python/compare/google-cloud-alloydb-v0.3.14...google-cloud-alloydb-v0.3.15) (2024-10-24) diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py index 7d28791e7569..f197f80165e7 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.15" # {x-release-please-version} +__version__ = "0.3.16" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py index 7d28791e7569..f197f80165e7 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.15" # {x-release-please-version} +__version__ = "0.3.16" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py index ac1c5be463ff..6b93cfa2f619 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py @@ -654,36 +654,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AlloyDBAdminClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -693,13 +663,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AlloyDBAdminClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py index 7d28791e7569..f197f80165e7 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.15" # {x-release-please-version} +__version__ = "0.3.16" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/services/alloy_db_admin/client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/services/alloy_db_admin/client.py index a53ef8c153df..1ccb8d449c00 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/services/alloy_db_admin/client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/services/alloy_db_admin/client.py @@ -654,36 +654,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AlloyDBAdminClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -693,13 +663,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AlloyDBAdminClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py index 7d28791e7569..f197f80165e7 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.15" # {x-release-please-version} +__version__ = "0.3.16" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py index 266026c341ee..13c5d0416d4a 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py @@ -654,36 +654,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AlloyDBAdminClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -693,13 +663,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AlloyDBAdminClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json index 97f6c465c6c3..6047286a1851 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.15" + "version": "0.3.16" }, "snippets": [ { diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json index f72c51c8e224..411b7b8cde0b 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.15" + "version": "0.3.16" }, "snippets": [ { diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json index 7a908eddae8e..7f87f6f35223 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.15" + "version": "0.3.16" }, "snippets": [ { diff --git a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py index 78403dac756e..a86f8d80f942 100644 --- a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py +++ b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py @@ -323,86 +323,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), - (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1alpha/test_alloy_db_admin.py b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1alpha/test_alloy_db_admin.py index aece66425791..b7cc318f1f29 100644 --- a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1alpha/test_alloy_db_admin.py +++ b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1alpha/test_alloy_db_admin.py @@ -323,86 +323,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), - (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1beta/test_alloy_db_admin.py b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1beta/test_alloy_db_admin.py index ad8be746aa06..b0d9cac2f7f8 100644 --- a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1beta/test_alloy_db_admin.py +++ b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1beta/test_alloy_db_admin.py @@ -323,86 +323,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AlloyDBAdminClient, transports.AlloyDBAdminGrpcTransport, "grpc"), - (AlloyDBAdminClient, transports.AlloyDBAdminRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-api-gateway/CHANGELOG.md b/packages/google-cloud-api-gateway/CHANGELOG.md index 02377a0376ca..ec0fe0b0db60 100644 --- a/packages/google-cloud-api-gateway/CHANGELOG.md +++ b/packages/google-cloud-api-gateway/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-gateway-v1.10.0...google-cloud-api-gateway-v1.10.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [1.10.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-gateway-v1.9.5...google-cloud-api-gateway-v1.10.0) (2024-10-24) diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway/gapic_version.py b/packages/google-cloud-api-gateway/google/cloud/apigateway/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway/gapic_version.py +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_version.py b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_version.py +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/client.py b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/client.py index d3ad4c8f4101..83f187d100d2 100644 --- a/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/client.py +++ b/packages/google-cloud-api-gateway/google/cloud/apigateway_v1/services/api_gateway_service/client.py @@ -562,36 +562,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ApiGatewayServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -601,13 +571,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ApiGatewayServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-api-gateway/samples/generated_samples/snippet_metadata_google.cloud.apigateway.v1.json b/packages/google-cloud-api-gateway/samples/generated_samples/snippet_metadata_google.cloud.apigateway.v1.json index 0e96fa0e231b..8a5e1a18b8e1 100644 --- a/packages/google-cloud-api-gateway/samples/generated_samples/snippet_metadata_google.cloud.apigateway.v1.json +++ b/packages/google-cloud-api-gateway/samples/generated_samples/snippet_metadata_google.cloud.apigateway.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-api-gateway", - "version": "1.10.0" + "version": "1.10.1" }, "snippets": [ { diff --git a/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py b/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py index 37e8d72a2b43..2dfe86359e2c 100644 --- a/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py +++ b/packages/google-cloud-api-gateway/tests/unit/gapic/apigateway_v1/test_api_gateway_service.py @@ -340,86 +340,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ApiGatewayServiceClient, transports.ApiGatewayServiceGrpcTransport, "grpc"), - (ApiGatewayServiceClient, transports.ApiGatewayServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-api-keys/CHANGELOG.md b/packages/google-cloud-api-keys/CHANGELOG.md index 27afb860d5de..237cb1c30ffa 100644 --- a/packages/google-cloud-api-keys/CHANGELOG.md +++ b/packages/google-cloud-api-keys/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-keys-v0.5.12...google-cloud-api-keys-v0.5.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.5.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-keys-v0.5.11...google-cloud-api-keys-v0.5.12) (2024-10-24) diff --git a/packages/google-cloud-api-keys/google/cloud/api_keys/gapic_version.py b/packages/google-cloud-api-keys/google/cloud/api_keys/gapic_version.py index cc43a639a105..bf678492aaad 100644 --- a/packages/google-cloud-api-keys/google/cloud/api_keys/gapic_version.py +++ b/packages/google-cloud-api-keys/google/cloud/api_keys/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.12" # {x-release-please-version} +__version__ = "0.5.13" # {x-release-please-version} diff --git a/packages/google-cloud-api-keys/google/cloud/api_keys_v2/gapic_version.py b/packages/google-cloud-api-keys/google/cloud/api_keys_v2/gapic_version.py index cc43a639a105..bf678492aaad 100644 --- a/packages/google-cloud-api-keys/google/cloud/api_keys_v2/gapic_version.py +++ b/packages/google-cloud-api-keys/google/cloud/api_keys_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.12" # {x-release-please-version} +__version__ = "0.5.13" # {x-release-please-version} diff --git a/packages/google-cloud-api-keys/google/cloud/api_keys_v2/services/api_keys/client.py b/packages/google-cloud-api-keys/google/cloud/api_keys_v2/services/api_keys/client.py index 9e6146d5a254..544a083e78ed 100644 --- a/packages/google-cloud-api-keys/google/cloud/api_keys_v2/services/api_keys/client.py +++ b/packages/google-cloud-api-keys/google/cloud/api_keys_v2/services/api_keys/client.py @@ -466,36 +466,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ApiKeysClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -505,13 +475,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ApiKeysClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-api-keys/samples/generated_samples/snippet_metadata_google.api.apikeys.v2.json b/packages/google-cloud-api-keys/samples/generated_samples/snippet_metadata_google.api.apikeys.v2.json index 0561851dc9bd..da595c436b65 100644 --- a/packages/google-cloud-api-keys/samples/generated_samples/snippet_metadata_google.api.apikeys.v2.json +++ b/packages/google-cloud-api-keys/samples/generated_samples/snippet_metadata_google.api.apikeys.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-api-keys", - "version": "0.5.12" + "version": "0.5.13" }, "snippets": [ { diff --git a/packages/google-cloud-api-keys/tests/unit/gapic/api_keys_v2/test_api_keys.py b/packages/google-cloud-api-keys/tests/unit/gapic/api_keys_v2/test_api_keys.py index facc09136402..699bfd1d45fa 100644 --- a/packages/google-cloud-api-keys/tests/unit/gapic/api_keys_v2/test_api_keys.py +++ b/packages/google-cloud-api-keys/tests/unit/gapic/api_keys_v2/test_api_keys.py @@ -296,86 +296,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ApiKeysClient, transports.ApiKeysGrpcTransport, "grpc"), - (ApiKeysClient, transports.ApiKeysRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apigee-connect/CHANGELOG.md b/packages/google-cloud-apigee-connect/CHANGELOG.md index af6cc52447e3..8bf7967b4903 100644 --- a/packages/google-cloud-apigee-connect/CHANGELOG.md +++ b/packages/google-cloud-apigee-connect/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apigee-connect-v1.10.0...google-cloud-apigee-connect-v1.10.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [1.10.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apigee-connect-v1.9.5...google-cloud-apigee-connect-v1.10.0) (2024-10-24) diff --git a/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect/gapic_version.py b/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect/gapic_version.py +++ b/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/gapic_version.py b/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/gapic_version.py +++ b/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/services/connection_service/client.py b/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/services/connection_service/client.py index 8b0713d63ed3..57386b00cd6d 100644 --- a/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/services/connection_service/client.py +++ b/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/services/connection_service/client.py @@ -456,36 +456,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConnectionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -495,13 +465,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ConnectionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/services/tether/client.py b/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/services/tether/client.py index 7b651a854222..76e2ab733e96 100644 --- a/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/services/tether/client.py +++ b/packages/google-cloud-apigee-connect/google/cloud/apigeeconnect_v1/services/tether/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TetherClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TetherClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apigee-connect/samples/generated_samples/snippet_metadata_google.cloud.apigeeconnect.v1.json b/packages/google-cloud-apigee-connect/samples/generated_samples/snippet_metadata_google.cloud.apigeeconnect.v1.json index 818baf25c308..c859fe599d2a 100644 --- a/packages/google-cloud-apigee-connect/samples/generated_samples/snippet_metadata_google.cloud.apigeeconnect.v1.json +++ b/packages/google-cloud-apigee-connect/samples/generated_samples/snippet_metadata_google.cloud.apigeeconnect.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-apigee-connect", - "version": "1.10.0" + "version": "1.10.1" }, "snippets": [ { diff --git a/packages/google-cloud-apigee-connect/tests/unit/gapic/apigeeconnect_v1/test_connection_service.py b/packages/google-cloud-apigee-connect/tests/unit/gapic/apigeeconnect_v1/test_connection_service.py index 355799758d93..e9418bd984a8 100644 --- a/packages/google-cloud-apigee-connect/tests/unit/gapic/apigeeconnect_v1/test_connection_service.py +++ b/packages/google-cloud-apigee-connect/tests/unit/gapic/apigeeconnect_v1/test_connection_service.py @@ -322,85 +322,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ConnectionServiceClient, transports.ConnectionServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apigee-connect/tests/unit/gapic/apigeeconnect_v1/test_tether.py b/packages/google-cloud-apigee-connect/tests/unit/gapic/apigeeconnect_v1/test_tether.py index eddc93ede74a..9018fd010c76 100644 --- a/packages/google-cloud-apigee-connect/tests/unit/gapic/apigeeconnect_v1/test_tether.py +++ b/packages/google-cloud-apigee-connect/tests/unit/gapic/apigeeconnect_v1/test_tether.py @@ -279,85 +279,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TetherClient, transports.TetherGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apigee-registry/CHANGELOG.md b/packages/google-cloud-apigee-registry/CHANGELOG.md index 6ae1c2c83460..488b4cfd17bd 100644 --- a/packages/google-cloud-apigee-registry/CHANGELOG.md +++ b/packages/google-cloud-apigee-registry/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.6.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apigee-registry-v0.6.12...google-cloud-apigee-registry-v0.6.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.6.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apigee-registry-v0.6.11...google-cloud-apigee-registry-v0.6.12) (2024-10-24) diff --git a/packages/google-cloud-apigee-registry/google/cloud/apigee_registry/gapic_version.py b/packages/google-cloud-apigee-registry/google/cloud/apigee_registry/gapic_version.py index 44e5c049e336..b72badcc1eca 100644 --- a/packages/google-cloud-apigee-registry/google/cloud/apigee_registry/gapic_version.py +++ b/packages/google-cloud-apigee-registry/google/cloud/apigee_registry/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.12" # {x-release-please-version} +__version__ = "0.6.13" # {x-release-please-version} diff --git a/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/gapic_version.py b/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/gapic_version.py index 44e5c049e336..b72badcc1eca 100644 --- a/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/gapic_version.py +++ b/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.12" # {x-release-please-version} +__version__ = "0.6.13" # {x-release-please-version} diff --git a/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/services/provisioning/client.py b/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/services/provisioning/client.py index b4130fca7e63..aeaea4f8ba3f 100644 --- a/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/services/provisioning/client.py +++ b/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/services/provisioning/client.py @@ -469,36 +469,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ProvisioningClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -508,13 +478,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ProvisioningClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/services/registry/client.py b/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/services/registry/client.py index 7e1b6e6ea32c..43b0a11b2a0e 100644 --- a/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/services/registry/client.py +++ b/packages/google-cloud-apigee-registry/google/cloud/apigee_registry_v1/services/registry/client.py @@ -566,36 +566,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegistryClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -605,13 +575,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegistryClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apigee-registry/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json b/packages/google-cloud-apigee-registry/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json index a1ac0971c707..70bba77cb438 100644 --- a/packages/google-cloud-apigee-registry/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json +++ b/packages/google-cloud-apigee-registry/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-apigee-registry", - "version": "0.6.12" + "version": "0.6.13" }, "snippets": [ { diff --git a/packages/google-cloud-apigee-registry/tests/unit/gapic/apigee_registry_v1/test_provisioning.py b/packages/google-cloud-apigee-registry/tests/unit/gapic/apigee_registry_v1/test_provisioning.py index 60c06698ca91..962e61a891b1 100644 --- a/packages/google-cloud-apigee-registry/tests/unit/gapic/apigee_registry_v1/test_provisioning.py +++ b/packages/google-cloud-apigee-registry/tests/unit/gapic/apigee_registry_v1/test_provisioning.py @@ -318,86 +318,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc"), - (ProvisioningClient, transports.ProvisioningRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apigee-registry/tests/unit/gapic/apigee_registry_v1/test_registry.py b/packages/google-cloud-apigee-registry/tests/unit/gapic/apigee_registry_v1/test_registry.py index 5b7f7065e3d5..d5e5078e6acc 100644 --- a/packages/google-cloud-apigee-registry/tests/unit/gapic/apigee_registry_v1/test_registry.py +++ b/packages/google-cloud-apigee-registry/tests/unit/gapic/apigee_registry_v1/test_registry.py @@ -299,86 +299,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegistryClient, transports.RegistryGrpcTransport, "grpc"), - (RegistryClient, transports.RegistryRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apihub/CHANGELOG.md b/packages/google-cloud-apihub/CHANGELOG.md index a85df21dd103..8f74ed60de4b 100644 --- a/packages/google-cloud-apihub/CHANGELOG.md +++ b/packages/google-cloud-apihub/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.2.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apihub-v0.2.1...google-cloud-apihub-v0.2.2) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.2.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apihub-v0.2.0...google-cloud-apihub-v0.2.1) (2024-10-24) diff --git a/packages/google-cloud-apihub/google/cloud/apihub/gapic_version.py b/packages/google-cloud-apihub/google/cloud/apihub/gapic_version.py index 6d8247638d59..d1a1a883babd 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub/gapic_version.py +++ b/packages/google-cloud-apihub/google/cloud/apihub/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.1" # {x-release-please-version} +__version__ = "0.2.2" # {x-release-please-version} diff --git a/packages/google-cloud-apihub/google/cloud/apihub_v1/gapic_version.py b/packages/google-cloud-apihub/google/cloud/apihub_v1/gapic_version.py index 6d8247638d59..d1a1a883babd 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub_v1/gapic_version.py +++ b/packages/google-cloud-apihub/google/cloud/apihub_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.1" # {x-release-please-version} +__version__ = "0.2.2" # {x-release-please-version} diff --git a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub/client.py b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub/client.py index 5aba7786ce4c..dc5bfa82b1f8 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub/client.py +++ b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub/client.py @@ -630,36 +630,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ApiHubClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -669,13 +639,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ApiHubClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub_dependencies/client.py b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub_dependencies/client.py index a0f477bdc990..64a45030eb07 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub_dependencies/client.py +++ b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub_dependencies/client.py @@ -488,36 +488,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ApiHubDependenciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -527,13 +497,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ApiHubDependenciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub_plugin/client.py b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub_plugin/client.py index 4a266b8071d9..f4cebeb8cb2f 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub_plugin/client.py +++ b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/api_hub_plugin/client.py @@ -479,36 +479,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ApiHubPluginClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -518,13 +488,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ApiHubPluginClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/host_project_registration_service/client.py b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/host_project_registration_service/client.py index 1aaa11b52562..e977d349f283 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/host_project_registration_service/client.py +++ b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/host_project_registration_service/client.py @@ -470,36 +470,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = HostProjectRegistrationServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -509,13 +479,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or HostProjectRegistrationServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/linting_service/client.py b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/linting_service/client.py index 418f3bdac4cc..6e65e8a84af9 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/linting_service/client.py +++ b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/linting_service/client.py @@ -486,36 +486,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LintingServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -525,13 +495,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or LintingServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/provisioning/client.py b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/provisioning/client.py index 187144d07e16..3ac25e6aa355 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/provisioning/client.py +++ b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/provisioning/client.py @@ -462,36 +462,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ProvisioningClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -501,13 +471,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ProvisioningClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/runtime_project_attachment_service/client.py b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/runtime_project_attachment_service/client.py index 940a4ce73410..16f69c687758 100644 --- a/packages/google-cloud-apihub/google/cloud/apihub_v1/services/runtime_project_attachment_service/client.py +++ b/packages/google-cloud-apihub/google/cloud/apihub_v1/services/runtime_project_attachment_service/client.py @@ -470,36 +470,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RuntimeProjectAttachmentServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -509,13 +479,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RuntimeProjectAttachmentServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apihub/samples/generated_samples/snippet_metadata_google.cloud.apihub.v1.json b/packages/google-cloud-apihub/samples/generated_samples/snippet_metadata_google.cloud.apihub.v1.json index 54afd714fa78..208b34aaaa8e 100644 --- a/packages/google-cloud-apihub/samples/generated_samples/snippet_metadata_google.cloud.apihub.v1.json +++ b/packages/google-cloud-apihub/samples/generated_samples/snippet_metadata_google.cloud.apihub.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-apihub", - "version": "0.2.1" + "version": "0.2.2" }, "snippets": [ { diff --git a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub.py b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub.py index 5a2dc217445b..8557fbc9ac5f 100644 --- a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub.py +++ b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub.py @@ -276,85 +276,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ApiHubClient, transports.ApiHubRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub_dependencies.py b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub_dependencies.py index 96280c9c8baf..576d49cc9b83 100644 --- a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub_dependencies.py +++ b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub_dependencies.py @@ -329,85 +329,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ApiHubDependenciesClient, transports.ApiHubDependenciesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub_plugin.py b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub_plugin.py index a7d41bc5fed0..51b127a5a5f7 100644 --- a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub_plugin.py +++ b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_api_hub_plugin.py @@ -298,85 +298,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ApiHubPluginClient, transports.ApiHubPluginRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_host_project_registration_service.py b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_host_project_registration_service.py index bdfcb57e6cf5..c5d1ab19ecec 100644 --- a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_host_project_registration_service.py +++ b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_host_project_registration_service.py @@ -347,89 +347,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - HostProjectRegistrationServiceClient, - transports.HostProjectRegistrationServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_linting_service.py b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_linting_service.py index ad5cd2e5419b..3dd2b4a666d9 100644 --- a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_linting_service.py +++ b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_linting_service.py @@ -314,85 +314,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (LintingServiceClient, transports.LintingServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_provisioning.py b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_provisioning.py index cdff93952823..aea58fb4b312 100644 --- a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_provisioning.py +++ b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_provisioning.py @@ -305,85 +305,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProvisioningClient, transports.ProvisioningRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_runtime_project_attachment_service.py b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_runtime_project_attachment_service.py index accf183648a8..9ca7085c4847 100644 --- a/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_runtime_project_attachment_service.py +++ b/packages/google-cloud-apihub/tests/unit/gapic/apihub_v1/test_runtime_project_attachment_service.py @@ -351,89 +351,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RuntimeProjectAttachmentServiceClient, - transports.RuntimeProjectAttachmentServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-appengine-admin/CHANGELOG.md b/packages/google-cloud-appengine-admin/CHANGELOG.md index 1d2a74f14b43..8d5b90f8b6c5 100644 --- a/packages/google-cloud-appengine-admin/CHANGELOG.md +++ b/packages/google-cloud-appengine-admin/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.12.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-appengine-admin-v1.12.0...google-cloud-appengine-admin-v1.12.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [1.12.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-appengine-admin-v1.11.5...google-cloud-appengine-admin-v1.12.0) (2024-10-24) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin/gapic_version.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin/gapic_version.py index 739fdfae141c..49ddc22ee702 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin/gapic_version.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.0" # {x-release-please-version} +__version__ = "1.12.1" # {x-release-please-version} diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/gapic_version.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/gapic_version.py index 739fdfae141c..49ddc22ee702 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/gapic_version.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.0" # {x-release-please-version} +__version__ = "1.12.1" # {x-release-please-version} diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/client.py index 5010433228ac..8c9c44b9389d 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/client.py @@ -441,36 +441,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ApplicationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -480,13 +450,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ApplicationsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py index e2633508c5c4..fab20c6c3455 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py @@ -446,36 +446,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AuthorizedCertificatesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -485,13 +455,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AuthorizedCertificatesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/client.py index 64df5a7c08c9..c020391620e7 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AuthorizedDomainsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AuthorizedDomainsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/client.py index cfda1bd8fedb..7d180628344e 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/client.py @@ -444,36 +444,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DomainMappingsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -483,13 +453,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DomainMappingsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/client.py index ac94c119d5e5..0dcffd4dc2eb 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/client.py @@ -449,36 +449,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = FirewallClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -488,13 +458,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or FirewallClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/client.py index cb551f26c8f2..7463d2db4d74 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/client.py @@ -467,36 +467,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InstancesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -506,13 +476,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InstancesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/client.py index a4440b5042fe..2ecb6e192e10 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/client.py @@ -443,36 +443,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ServicesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -482,13 +452,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ServicesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/client.py index 20dfb5b039de..bdee4bba3e16 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/client.py @@ -445,36 +445,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = VersionsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -484,13 +454,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or VersionsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-appengine-admin/samples/generated_samples/snippet_metadata_google.appengine.v1.json b/packages/google-cloud-appengine-admin/samples/generated_samples/snippet_metadata_google.appengine.v1.json index ed1da0c26d00..81c672284b63 100644 --- a/packages/google-cloud-appengine-admin/samples/generated_samples/snippet_metadata_google.appengine.v1.json +++ b/packages/google-cloud-appengine-admin/samples/generated_samples/snippet_metadata_google.appengine.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-appengine-admin", - "version": "1.12.0" + "version": "1.12.1" }, "snippets": [ { diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_applications.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_applications.py index 2b0a56308357..b2b59b82e43c 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_applications.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_applications.py @@ -315,86 +315,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"), - (ApplicationsClient, transports.ApplicationsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py index 416cae547ed4..6259710fa02c 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py @@ -337,94 +337,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AuthorizedCertificatesClient, - transports.AuthorizedCertificatesGrpcTransport, - "grpc", - ), - ( - AuthorizedCertificatesClient, - transports.AuthorizedCertificatesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py index 35496281ee94..60f3bb84d664 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py @@ -327,86 +327,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"), - (AuthorizedDomainsClient, transports.AuthorizedDomainsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py index a9e2c6797157..6cefee35a9e5 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py @@ -331,86 +331,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"), - (DomainMappingsClient, transports.DomainMappingsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_firewall.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_firewall.py index 5ab189956a41..44e92176cf49 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_firewall.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_firewall.py @@ -291,86 +291,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (FirewallClient, transports.FirewallGrpcTransport, "grpc"), - (FirewallClient, transports.FirewallRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_instances.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_instances.py index fa833efec1f6..7abe36da166f 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_instances.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_instances.py @@ -306,86 +306,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (InstancesClient, transports.InstancesGrpcTransport, "grpc"), - (InstancesClient, transports.InstancesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_services.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_services.py index 90e7a55b0a3b..6517ea9f2963 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_services.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_services.py @@ -304,86 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc"), - (ServicesClient, transports.ServicesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_versions.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_versions.py index 99b8d859ab3e..1a379fbd916d 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_versions.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_versions.py @@ -306,86 +306,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsClient, transports.VersionsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-apphub/CHANGELOG.md b/packages/google-cloud-apphub/CHANGELOG.md index f5ab5c892704..d3ab72407619 100644 --- a/packages/google-cloud-apphub/CHANGELOG.md +++ b/packages/google-cloud-apphub/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apphub-v0.1.3...google-cloud-apphub-v0.1.4) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [0.1.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apphub-v0.1.2...google-cloud-apphub-v0.1.3) (2024-10-24) diff --git a/packages/google-cloud-apphub/google/cloud/apphub/gapic_version.py b/packages/google-cloud-apphub/google/cloud/apphub/gapic_version.py index 114e40645800..937ede8823ef 100644 --- a/packages/google-cloud-apphub/google/cloud/apphub/gapic_version.py +++ b/packages/google-cloud-apphub/google/cloud/apphub/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.3" # {x-release-please-version} +__version__ = "0.1.4" # {x-release-please-version} diff --git a/packages/google-cloud-apphub/google/cloud/apphub_v1/gapic_version.py b/packages/google-cloud-apphub/google/cloud/apphub_v1/gapic_version.py index 114e40645800..937ede8823ef 100644 --- a/packages/google-cloud-apphub/google/cloud/apphub_v1/gapic_version.py +++ b/packages/google-cloud-apphub/google/cloud/apphub_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.3" # {x-release-please-version} +__version__ = "0.1.4" # {x-release-please-version} diff --git a/packages/google-cloud-apphub/google/cloud/apphub_v1/services/app_hub/client.py b/packages/google-cloud-apphub/google/cloud/apphub_v1/services/app_hub/client.py index cffae475bf73..9e1aef923d80 100644 --- a/packages/google-cloud-apphub/google/cloud/apphub_v1/services/app_hub/client.py +++ b/packages/google-cloud-apphub/google/cloud/apphub_v1/services/app_hub/client.py @@ -596,36 +596,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AppHubClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -635,13 +605,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AppHubClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-apphub/samples/generated_samples/snippet_metadata_google.cloud.apphub.v1.json b/packages/google-cloud-apphub/samples/generated_samples/snippet_metadata_google.cloud.apphub.v1.json index 2d91af205a2d..7f54a8e2552a 100644 --- a/packages/google-cloud-apphub/samples/generated_samples/snippet_metadata_google.cloud.apphub.v1.json +++ b/packages/google-cloud-apphub/samples/generated_samples/snippet_metadata_google.cloud.apphub.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-apphub", - "version": "0.1.3" + "version": "0.1.4" }, "snippets": [ { diff --git a/packages/google-cloud-apphub/tests/unit/gapic/apphub_v1/test_app_hub.py b/packages/google-cloud-apphub/tests/unit/gapic/apphub_v1/test_app_hub.py index d40134958924..cca807929893 100644 --- a/packages/google-cloud-apphub/tests/unit/gapic/apphub_v1/test_app_hub.py +++ b/packages/google-cloud-apphub/tests/unit/gapic/apphub_v1/test_app_hub.py @@ -310,86 +310,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AppHubClient, transports.AppHubGrpcTransport, "grpc"), - (AppHubClient, transports.AppHubRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-asset/CHANGELOG.md b/packages/google-cloud-asset/CHANGELOG.md index 1fb8f229bbf6..a2b1971a5d85 100644 --- a/packages/google-cloud-asset/CHANGELOG.md +++ b/packages/google-cloud-asset/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-asset/#history +## [3.27.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-asset-v3.27.0...google-cloud-asset-v3.27.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [3.27.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-asset-v3.26.4...google-cloud-asset-v3.27.0) (2024-10-24) diff --git a/packages/google-cloud-asset/google/cloud/asset/gapic_version.py b/packages/google-cloud-asset/google/cloud/asset/gapic_version.py index 3d01951c9fa8..7af2fa694463 100644 --- a/packages/google-cloud-asset/google/cloud/asset/gapic_version.py +++ b/packages/google-cloud-asset/google/cloud/asset/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.27.0" # {x-release-please-version} +__version__ = "3.27.1" # {x-release-please-version} diff --git a/packages/google-cloud-asset/google/cloud/asset_v1/gapic_version.py b/packages/google-cloud-asset/google/cloud/asset_v1/gapic_version.py index 3d01951c9fa8..7af2fa694463 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1/gapic_version.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.27.0" # {x-release-please-version} +__version__ = "3.27.1" # {x-release-please-version} diff --git a/packages/google-cloud-asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/google-cloud-asset/google/cloud/asset_v1/services/asset_service/client.py index 2b8df9993c3c..ab8f4a588fee 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1/services/asset_service/client.py @@ -569,36 +569,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AssetServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -608,13 +578,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AssetServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-asset/google/cloud/asset_v1p1beta1/gapic_version.py b/packages/google-cloud-asset/google/cloud/asset_v1p1beta1/gapic_version.py index 3d01951c9fa8..7af2fa694463 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1p1beta1/gapic_version.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1p1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.27.0" # {x-release-please-version} +__version__ = "3.27.1" # {x-release-please-version} diff --git a/packages/google-cloud-asset/google/cloud/asset_v1p1beta1/services/asset_service/client.py b/packages/google-cloud-asset/google/cloud/asset_v1p1beta1/services/asset_service/client.py index 2fcc58f03271..ef68719ec45e 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1p1beta1/services/asset_service/client.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1p1beta1/services/asset_service/client.py @@ -439,36 +439,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AssetServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -478,13 +448,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AssetServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-asset/google/cloud/asset_v1p2beta1/gapic_version.py b/packages/google-cloud-asset/google/cloud/asset_v1p2beta1/gapic_version.py index 3d01951c9fa8..7af2fa694463 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1p2beta1/gapic_version.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1p2beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.27.0" # {x-release-please-version} +__version__ = "3.27.1" # {x-release-please-version} diff --git a/packages/google-cloud-asset/google/cloud/asset_v1p2beta1/services/asset_service/client.py b/packages/google-cloud-asset/google/cloud/asset_v1p2beta1/services/asset_service/client.py index e6ad044ef902..6a8d3d767b4a 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1p2beta1/services/asset_service/client.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1p2beta1/services/asset_service/client.py @@ -455,36 +455,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AssetServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -494,13 +464,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AssetServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-asset/google/cloud/asset_v1p4beta1/gapic_version.py b/packages/google-cloud-asset/google/cloud/asset_v1p4beta1/gapic_version.py index f0856cadb731..41c4b1117b02 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1p4beta1/gapic_version.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1p4beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.27.0" # {x-release-please-version} +__version__ = "3.27.1" # {x-release-please-version} diff --git a/packages/google-cloud-asset/google/cloud/asset_v1p5beta1/gapic_version.py b/packages/google-cloud-asset/google/cloud/asset_v1p5beta1/gapic_version.py index 3d01951c9fa8..7af2fa694463 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1p5beta1/gapic_version.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1p5beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.27.0" # {x-release-please-version} +__version__ = "3.27.1" # {x-release-please-version} diff --git a/packages/google-cloud-asset/google/cloud/asset_v1p5beta1/services/asset_service/client.py b/packages/google-cloud-asset/google/cloud/asset_v1p5beta1/services/asset_service/client.py index 63c2052ad74d..ce6688ec0ca9 100644 --- a/packages/google-cloud-asset/google/cloud/asset_v1p5beta1/services/asset_service/client.py +++ b/packages/google-cloud-asset/google/cloud/asset_v1p5beta1/services/asset_service/client.py @@ -505,36 +505,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AssetServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -544,13 +514,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AssetServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json b/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json index c7fd85da945a..adaf8664d0c3 100644 --- a/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json +++ b/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-asset", - "version": "3.27.0" + "version": "3.27.1" }, "snippets": [ { diff --git a/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json b/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json index 32920338db60..2842e3347574 100644 --- a/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json +++ b/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-asset", - "version": "3.27.0" + "version": "3.27.1" }, "snippets": [ { diff --git a/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json b/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json index 2201c8e0f90f..e542094192d6 100644 --- a/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json +++ b/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-asset", - "version": "3.27.0" + "version": "3.27.1" }, "snippets": [ { diff --git a/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json b/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json index 21a9be2abf2c..902ea38b5ad3 100644 --- a/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json +++ b/packages/google-cloud-asset/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-asset", - "version": "3.27.0" + "version": "3.27.1" }, "snippets": [ { diff --git a/packages/google-cloud-asset/tests/unit/gapic/asset_v1/test_asset_service.py b/packages/google-cloud-asset/tests/unit/gapic/asset_v1/test_asset_service.py index 917eb9774d49..1be19ffc7a4e 100644 --- a/packages/google-cloud-asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/packages/google-cloud-asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -318,86 +318,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-asset/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py b/packages/google-cloud-asset/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py index de10f93c61f2..186e045cb8ba 100644 --- a/packages/google-cloud-asset/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py +++ b/packages/google-cloud-asset/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py @@ -304,86 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-asset/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py b/packages/google-cloud-asset/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py index 45f5d5e13e95..b37fea78b51c 100644 --- a/packages/google-cloud-asset/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py +++ b/packages/google-cloud-asset/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py @@ -304,86 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-asset/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py b/packages/google-cloud-asset/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py index fb1bc8815620..016ff1d1040d 100644 --- a/packages/google-cloud-asset/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py +++ b/packages/google-cloud-asset/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py @@ -305,86 +305,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-assured-workloads/CHANGELOG.md b/packages/google-cloud-assured-workloads/CHANGELOG.md index 94edf9a49077..f6763ed52eda 100644 --- a/packages/google-cloud-assured-workloads/CHANGELOG.md +++ b/packages/google-cloud-assured-workloads/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.13.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-assured-workloads-v1.13.0...google-cloud-assured-workloads-v1.13.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([85c7512](https://github.com/googleapis/google-cloud-python/commit/85c7512bbdde2b9cc60b4ad42b8c36c4558a07a5)) + ## [1.13.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-assured-workloads-v1.12.5...google-cloud-assured-workloads-v1.13.0) (2024-10-24) diff --git a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads/gapic_version.py b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads/gapic_version.py index 43155ded0db3..0b9427f4e8a5 100644 --- a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads/gapic_version.py +++ b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.0" # {x-release-please-version} +__version__ = "1.13.1" # {x-release-please-version} diff --git a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1/gapic_version.py b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1/gapic_version.py index 43155ded0db3..0b9427f4e8a5 100644 --- a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1/gapic_version.py +++ b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.0" # {x-release-please-version} +__version__ = "1.13.1" # {x-release-please-version} diff --git a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1/services/assured_workloads_service/client.py b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1/services/assured_workloads_service/client.py index 1bf67c0c68e7..9e181474c909 100644 --- a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1/services/assured_workloads_service/client.py +++ b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1/services/assured_workloads_service/client.py @@ -493,36 +493,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AssuredWorkloadsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -532,13 +502,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AssuredWorkloadsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1beta1/gapic_version.py b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1beta1/gapic_version.py index 43155ded0db3..0b9427f4e8a5 100644 --- a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1beta1/gapic_version.py +++ b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.0" # {x-release-please-version} +__version__ = "1.13.1" # {x-release-please-version} diff --git a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1beta1/services/assured_workloads_service/client.py b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1beta1/services/assured_workloads_service/client.py index 1a3eec133330..49d2dac8051e 100644 --- a/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1beta1/services/assured_workloads_service/client.py +++ b/packages/google-cloud-assured-workloads/google/cloud/assuredworkloads_v1beta1/services/assured_workloads_service/client.py @@ -471,36 +471,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AssuredWorkloadsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -510,13 +480,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AssuredWorkloadsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-assured-workloads/samples/generated_samples/snippet_metadata_google.cloud.assuredworkloads.v1.json b/packages/google-cloud-assured-workloads/samples/generated_samples/snippet_metadata_google.cloud.assuredworkloads.v1.json index 124869c8d53a..329203fab093 100644 --- a/packages/google-cloud-assured-workloads/samples/generated_samples/snippet_metadata_google.cloud.assuredworkloads.v1.json +++ b/packages/google-cloud-assured-workloads/samples/generated_samples/snippet_metadata_google.cloud.assuredworkloads.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-assured-workloads", - "version": "1.13.0" + "version": "1.13.1" }, "snippets": [ { diff --git a/packages/google-cloud-assured-workloads/samples/generated_samples/snippet_metadata_google.cloud.assuredworkloads.v1beta1.json b/packages/google-cloud-assured-workloads/samples/generated_samples/snippet_metadata_google.cloud.assuredworkloads.v1beta1.json index d457c182715b..f857c8897b0f 100644 --- a/packages/google-cloud-assured-workloads/samples/generated_samples/snippet_metadata_google.cloud.assuredworkloads.v1beta1.json +++ b/packages/google-cloud-assured-workloads/samples/generated_samples/snippet_metadata_google.cloud.assuredworkloads.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-assured-workloads", - "version": "1.13.0" + "version": "1.13.1" }, "snippets": [ { diff --git a/packages/google-cloud-assured-workloads/tests/unit/gapic/assuredworkloads_v1/test_assured_workloads_service.py b/packages/google-cloud-assured-workloads/tests/unit/gapic/assuredworkloads_v1/test_assured_workloads_service.py index 772b3ebd44e0..7ba335b1db84 100644 --- a/packages/google-cloud-assured-workloads/tests/unit/gapic/assuredworkloads_v1/test_assured_workloads_service.py +++ b/packages/google-cloud-assured-workloads/tests/unit/gapic/assuredworkloads_v1/test_assured_workloads_service.py @@ -348,94 +348,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AssuredWorkloadsServiceClient, - transports.AssuredWorkloadsServiceGrpcTransport, - "grpc", - ), - ( - AssuredWorkloadsServiceClient, - transports.AssuredWorkloadsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-assured-workloads/tests/unit/gapic/assuredworkloads_v1beta1/test_assured_workloads_service.py b/packages/google-cloud-assured-workloads/tests/unit/gapic/assuredworkloads_v1beta1/test_assured_workloads_service.py index 0f073e6af917..94166e9a5540 100644 --- a/packages/google-cloud-assured-workloads/tests/unit/gapic/assuredworkloads_v1beta1/test_assured_workloads_service.py +++ b/packages/google-cloud-assured-workloads/tests/unit/gapic/assuredworkloads_v1beta1/test_assured_workloads_service.py @@ -348,94 +348,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AssuredWorkloadsServiceClient, - transports.AssuredWorkloadsServiceGrpcTransport, - "grpc", - ), - ( - AssuredWorkloadsServiceClient, - transports.AssuredWorkloadsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-automl/CHANGELOG.md b/packages/google-cloud-automl/CHANGELOG.md index 2d187a609841..419595e14315 100644 --- a/packages/google-cloud-automl/CHANGELOG.md +++ b/packages/google-cloud-automl/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-automl/#history +## [2.14.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-automl-v2.14.0...google-cloud-automl-v2.14.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [2.14.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-automl-v2.13.5...google-cloud-automl-v2.14.0) (2024-10-24) diff --git a/packages/google-cloud-automl/google/cloud/automl/gapic_version.py b/packages/google-cloud-automl/google/cloud/automl/gapic_version.py index 773005b00ca9..2523dfbe9e23 100644 --- a/packages/google-cloud-automl/google/cloud/automl/gapic_version.py +++ b/packages/google-cloud-automl/google/cloud/automl/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.0" # {x-release-please-version} +__version__ = "2.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-automl/google/cloud/automl_v1/gapic_version.py b/packages/google-cloud-automl/google/cloud/automl_v1/gapic_version.py index 773005b00ca9..2523dfbe9e23 100644 --- a/packages/google-cloud-automl/google/cloud/automl_v1/gapic_version.py +++ b/packages/google-cloud-automl/google/cloud/automl_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.0" # {x-release-please-version} +__version__ = "2.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-automl/google/cloud/automl_v1/services/auto_ml/client.py b/packages/google-cloud-automl/google/cloud/automl_v1/services/auto_ml/client.py index f75547d5642f..187d7c17a984 100644 --- a/packages/google-cloud-automl/google/cloud/automl_v1/services/auto_ml/client.py +++ b/packages/google-cloud-automl/google/cloud/automl_v1/services/auto_ml/client.py @@ -564,36 +564,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AutoMlClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -603,13 +573,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AutoMlClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-automl/google/cloud/automl_v1/services/prediction_service/client.py b/packages/google-cloud-automl/google/cloud/automl_v1/services/prediction_service/client.py index b8d837686197..ba4d427b59db 100644 --- a/packages/google-cloud-automl/google/cloud/automl_v1/services/prediction_service/client.py +++ b/packages/google-cloud-automl/google/cloud/automl_v1/services/prediction_service/client.py @@ -473,36 +473,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PredictionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -512,13 +482,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PredictionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-automl/google/cloud/automl_v1beta1/gapic_version.py b/packages/google-cloud-automl/google/cloud/automl_v1beta1/gapic_version.py index 773005b00ca9..2523dfbe9e23 100644 --- a/packages/google-cloud-automl/google/cloud/automl_v1beta1/gapic_version.py +++ b/packages/google-cloud-automl/google/cloud/automl_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.0" # {x-release-please-version} +__version__ = "2.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-automl/google/cloud/automl_v1beta1/services/auto_ml/client.py b/packages/google-cloud-automl/google/cloud/automl_v1beta1/services/auto_ml/client.py index cb77a70222f4..06f15fd1ec6f 100644 --- a/packages/google-cloud-automl/google/cloud/automl_v1beta1/services/auto_ml/client.py +++ b/packages/google-cloud-automl/google/cloud/automl_v1beta1/services/auto_ml/client.py @@ -623,36 +623,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AutoMlClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -662,13 +632,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AutoMlClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-automl/google/cloud/automl_v1beta1/services/prediction_service/client.py b/packages/google-cloud-automl/google/cloud/automl_v1beta1/services/prediction_service/client.py index b52f0c1c9c30..23ab0d0fe0ee 100644 --- a/packages/google-cloud-automl/google/cloud/automl_v1beta1/services/prediction_service/client.py +++ b/packages/google-cloud-automl/google/cloud/automl_v1beta1/services/prediction_service/client.py @@ -473,36 +473,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PredictionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -512,13 +482,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PredictionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-automl/samples/generated_samples/snippet_metadata_google.cloud.automl.v1.json b/packages/google-cloud-automl/samples/generated_samples/snippet_metadata_google.cloud.automl.v1.json index 2bd37e62c638..49126fa3a89d 100644 --- a/packages/google-cloud-automl/samples/generated_samples/snippet_metadata_google.cloud.automl.v1.json +++ b/packages/google-cloud-automl/samples/generated_samples/snippet_metadata_google.cloud.automl.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-automl", - "version": "2.14.0" + "version": "2.14.1" }, "snippets": [ { diff --git a/packages/google-cloud-automl/samples/generated_samples/snippet_metadata_google.cloud.automl.v1beta1.json b/packages/google-cloud-automl/samples/generated_samples/snippet_metadata_google.cloud.automl.v1beta1.json index fad8cd1411fa..a123a7bf2218 100644 --- a/packages/google-cloud-automl/samples/generated_samples/snippet_metadata_google.cloud.automl.v1beta1.json +++ b/packages/google-cloud-automl/samples/generated_samples/snippet_metadata_google.cloud.automl.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-automl", - "version": "2.14.0" + "version": "2.14.1" }, "snippets": [ { diff --git a/packages/google-cloud-automl/tests/unit/gapic/automl_v1/test_auto_ml.py b/packages/google-cloud-automl/tests/unit/gapic/automl_v1/test_auto_ml.py index 8953f9f75560..b93fc9fb0fbc 100644 --- a/packages/google-cloud-automl/tests/unit/gapic/automl_v1/test_auto_ml.py +++ b/packages/google-cloud-automl/tests/unit/gapic/automl_v1/test_auto_ml.py @@ -309,86 +309,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AutoMlClient, transports.AutoMlGrpcTransport, "grpc"), - (AutoMlClient, transports.AutoMlRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-automl/tests/unit/gapic/automl_v1/test_prediction_service.py b/packages/google-cloud-automl/tests/unit/gapic/automl_v1/test_prediction_service.py index eb0968b4e1cf..619c77d51854 100644 --- a/packages/google-cloud-automl/tests/unit/gapic/automl_v1/test_prediction_service.py +++ b/packages/google-cloud-automl/tests/unit/gapic/automl_v1/test_prediction_service.py @@ -344,86 +344,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceClient, transports.PredictionServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-automl/tests/unit/gapic/automl_v1beta1/test_auto_ml.py b/packages/google-cloud-automl/tests/unit/gapic/automl_v1beta1/test_auto_ml.py index 1f591ddbef56..bf1e2924313b 100644 --- a/packages/google-cloud-automl/tests/unit/gapic/automl_v1beta1/test_auto_ml.py +++ b/packages/google-cloud-automl/tests/unit/gapic/automl_v1beta1/test_auto_ml.py @@ -319,86 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AutoMlClient, transports.AutoMlGrpcTransport, "grpc"), - (AutoMlClient, transports.AutoMlRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-automl/tests/unit/gapic/automl_v1beta1/test_prediction_service.py b/packages/google-cloud-automl/tests/unit/gapic/automl_v1beta1/test_prediction_service.py index 5ba19a19143b..16fc61240b14 100644 --- a/packages/google-cloud-automl/tests/unit/gapic/automl_v1beta1/test_prediction_service.py +++ b/packages/google-cloud-automl/tests/unit/gapic/automl_v1beta1/test_prediction_service.py @@ -345,86 +345,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), - (PredictionServiceClient, transports.PredictionServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-backupdr/CHANGELOG.md b/packages/google-cloud-backupdr/CHANGELOG.md index 51f47d25fb7b..756c19694ada 100644 --- a/packages/google-cloud-backupdr/CHANGELOG.md +++ b/packages/google-cloud-backupdr/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-backupdr-v0.1.5...google-cloud-backupdr-v0.1.6) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-backupdr-v0.1.4...google-cloud-backupdr-v0.1.5) (2024-10-24) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py b/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py index e9c4bb5650f3..51d2795b9d6b 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.5" # {x-release-please-version} +__version__ = "0.1.6" # {x-release-please-version} diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py index e9c4bb5650f3..51d2795b9d6b 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.5" # {x-release-please-version} +__version__ = "0.1.6" # {x-release-please-version} diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py index 62543a3803a5..cad43136427b 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py @@ -598,36 +598,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BackupDRClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -637,13 +607,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BackupDRClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json index f1bc38934c4e..4164339aa8cf 100644 --- a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json +++ b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-backupdr", - "version": "0.1.5" + "version": "0.1.6" }, "snippets": [ { diff --git a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py index 64bbae698abd..2a0ff4a24856 100644 --- a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py +++ b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py @@ -320,86 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BackupDRClient, transports.BackupDRGrpcTransport, "grpc"), - (BackupDRClient, transports.BackupDRRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bare-metal-solution/CHANGELOG.md b/packages/google-cloud-bare-metal-solution/CHANGELOG.md index 6a0534bd333c..c676874a043b 100644 --- a/packages/google-cloud-bare-metal-solution/CHANGELOG.md +++ b/packages/google-cloud-bare-metal-solution/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.8.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bare-metal-solution-v1.8.0...google-cloud-bare-metal-solution-v1.8.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [1.8.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bare-metal-solution-v1.7.5...google-cloud-bare-metal-solution-v1.8.0) (2024-10-24) diff --git a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution/gapic_version.py b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution/gapic_version.py index 4b114d153974..02874f69f4e5 100644 --- a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution/gapic_version.py +++ b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.8.0" # {x-release-please-version} +__version__ = "1.8.1" # {x-release-please-version} diff --git a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/gapic_version.py b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/gapic_version.py index 4b114d153974..02874f69f4e5 100644 --- a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/gapic_version.py +++ b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.8.0" # {x-release-please-version} +__version__ = "1.8.1" # {x-release-please-version} diff --git a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/client.py b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/client.py index c5896f656da2..60f10dbb0d74 100644 --- a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/client.py +++ b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/client.py @@ -830,36 +830,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BareMetalSolutionClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -869,13 +839,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BareMetalSolutionClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bare-metal-solution/samples/generated_samples/snippet_metadata_google.cloud.baremetalsolution.v2.json b/packages/google-cloud-bare-metal-solution/samples/generated_samples/snippet_metadata_google.cloud.baremetalsolution.v2.json index 649bd3e5c000..a1ea0708b18d 100644 --- a/packages/google-cloud-bare-metal-solution/samples/generated_samples/snippet_metadata_google.cloud.baremetalsolution.v2.json +++ b/packages/google-cloud-bare-metal-solution/samples/generated_samples/snippet_metadata_google.cloud.baremetalsolution.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bare-metal-solution", - "version": "1.8.0" + "version": "1.8.1" }, "snippets": [ { diff --git a/packages/google-cloud-bare-metal-solution/tests/unit/gapic/bare_metal_solution_v2/test_bare_metal_solution.py b/packages/google-cloud-bare-metal-solution/tests/unit/gapic/bare_metal_solution_v2/test_bare_metal_solution.py index 5a3c21a2ed2c..08d3d0b5e4ed 100644 --- a/packages/google-cloud-bare-metal-solution/tests/unit/gapic/bare_metal_solution_v2/test_bare_metal_solution.py +++ b/packages/google-cloud-bare-metal-solution/tests/unit/gapic/bare_metal_solution_v2/test_bare_metal_solution.py @@ -360,86 +360,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BareMetalSolutionClient, transports.BareMetalSolutionGrpcTransport, "grpc"), - (BareMetalSolutionClient, transports.BareMetalSolutionRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-batch/CHANGELOG.md b/packages/google-cloud-batch/CHANGELOG.md index 450b76079b16..b52788362d52 100644 --- a/packages/google-cloud-batch/CHANGELOG.md +++ b/packages/google-cloud-batch/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.17.31](https://github.com/googleapis/google-cloud-python/compare/google-cloud-batch-v0.17.30...google-cloud-batch-v0.17.31) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.17.30](https://github.com/googleapis/google-cloud-python/compare/google-cloud-batch-v0.17.29...google-cloud-batch-v0.17.30) (2024-10-24) diff --git a/packages/google-cloud-batch/google/cloud/batch/gapic_version.py b/packages/google-cloud-batch/google/cloud/batch/gapic_version.py index 71eef09933f2..b6bd82a78613 100644 --- a/packages/google-cloud-batch/google/cloud/batch/gapic_version.py +++ b/packages/google-cloud-batch/google/cloud/batch/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.17.30" # {x-release-please-version} +__version__ = "0.17.31" # {x-release-please-version} diff --git a/packages/google-cloud-batch/google/cloud/batch_v1/gapic_version.py b/packages/google-cloud-batch/google/cloud/batch_v1/gapic_version.py index 71eef09933f2..b6bd82a78613 100644 --- a/packages/google-cloud-batch/google/cloud/batch_v1/gapic_version.py +++ b/packages/google-cloud-batch/google/cloud/batch_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.17.30" # {x-release-please-version} +__version__ = "0.17.31" # {x-release-please-version} diff --git a/packages/google-cloud-batch/google/cloud/batch_v1/services/batch_service/client.py b/packages/google-cloud-batch/google/cloud/batch_v1/services/batch_service/client.py index aa5242f0130a..22a7a7de0cb6 100644 --- a/packages/google-cloud-batch/google/cloud/batch_v1/services/batch_service/client.py +++ b/packages/google-cloud-batch/google/cloud/batch_v1/services/batch_service/client.py @@ -522,36 +522,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BatchServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -561,13 +531,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BatchServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-batch/google/cloud/batch_v1alpha/gapic_version.py b/packages/google-cloud-batch/google/cloud/batch_v1alpha/gapic_version.py index 71eef09933f2..b6bd82a78613 100644 --- a/packages/google-cloud-batch/google/cloud/batch_v1alpha/gapic_version.py +++ b/packages/google-cloud-batch/google/cloud/batch_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.17.30" # {x-release-please-version} +__version__ = "0.17.31" # {x-release-please-version} diff --git a/packages/google-cloud-batch/google/cloud/batch_v1alpha/services/batch_service/client.py b/packages/google-cloud-batch/google/cloud/batch_v1alpha/services/batch_service/client.py index 81bc50a2c342..b8db242b68b7 100644 --- a/packages/google-cloud-batch/google/cloud/batch_v1alpha/services/batch_service/client.py +++ b/packages/google-cloud-batch/google/cloud/batch_v1alpha/services/batch_service/client.py @@ -550,36 +550,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BatchServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -589,13 +559,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BatchServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-batch/samples/generated_samples/snippet_metadata_google.cloud.batch.v1.json b/packages/google-cloud-batch/samples/generated_samples/snippet_metadata_google.cloud.batch.v1.json index cff9c2aa0e65..ee4fbd362887 100644 --- a/packages/google-cloud-batch/samples/generated_samples/snippet_metadata_google.cloud.batch.v1.json +++ b/packages/google-cloud-batch/samples/generated_samples/snippet_metadata_google.cloud.batch.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-batch", - "version": "0.17.30" + "version": "0.17.31" }, "snippets": [ { diff --git a/packages/google-cloud-batch/samples/generated_samples/snippet_metadata_google.cloud.batch.v1alpha.json b/packages/google-cloud-batch/samples/generated_samples/snippet_metadata_google.cloud.batch.v1alpha.json index f2488f4d433e..f52304810a06 100644 --- a/packages/google-cloud-batch/samples/generated_samples/snippet_metadata_google.cloud.batch.v1alpha.json +++ b/packages/google-cloud-batch/samples/generated_samples/snippet_metadata_google.cloud.batch.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-batch", - "version": "0.17.30" + "version": "0.17.31" }, "snippets": [ { diff --git a/packages/google-cloud-batch/tests/unit/gapic/batch_v1/test_batch_service.py b/packages/google-cloud-batch/tests/unit/gapic/batch_v1/test_batch_service.py index 288cdbdc16e4..6f372d5128c2 100644 --- a/packages/google-cloud-batch/tests/unit/gapic/batch_v1/test_batch_service.py +++ b/packages/google-cloud-batch/tests/unit/gapic/batch_v1/test_batch_service.py @@ -320,86 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BatchServiceClient, transports.BatchServiceGrpcTransport, "grpc"), - (BatchServiceClient, transports.BatchServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-batch/tests/unit/gapic/batch_v1alpha/test_batch_service.py b/packages/google-cloud-batch/tests/unit/gapic/batch_v1alpha/test_batch_service.py index 346750b7a162..d978de4f7fba 100644 --- a/packages/google-cloud-batch/tests/unit/gapic/batch_v1alpha/test_batch_service.py +++ b/packages/google-cloud-batch/tests/unit/gapic/batch_v1alpha/test_batch_service.py @@ -327,86 +327,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BatchServiceClient, transports.BatchServiceGrpcTransport, "grpc"), - (BatchServiceClient, transports.BatchServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md b/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md index 1ecda6b2271b..4a1308ce8490 100644 --- a/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appconnections-v0.4.12...google-cloud-beyondcorp-appconnections-v0.4.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.4.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appconnections-v0.4.11...google-cloud-beyondcorp-appconnections-v0.4.12) (2024-10-24) diff --git a/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections/gapic_version.py b/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections/gapic_version.py +++ b/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections_v1/gapic_version.py b/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections_v1/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections_v1/gapic_version.py +++ b/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections_v1/services/app_connections_service/client.py b/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections_v1/services/app_connections_service/client.py index afa938f3fc58..ffdcb843d0ff 100644 --- a/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections_v1/services/app_connections_service/client.py +++ b/packages/google-cloud-beyondcorp-appconnections/google/cloud/beyondcorp_appconnections_v1/services/app_connections_service/client.py @@ -535,36 +535,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AppConnectionsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -574,13 +544,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AppConnectionsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-beyondcorp-appconnections/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appconnections.v1.json b/packages/google-cloud-beyondcorp-appconnections/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appconnections.v1.json index 74f340dcda3d..2409ab52fa34 100644 --- a/packages/google-cloud-beyondcorp-appconnections/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appconnections.v1.json +++ b/packages/google-cloud-beyondcorp-appconnections/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appconnections.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-beyondcorp-appconnections", - "version": "0.4.12" + "version": "0.4.13" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-appconnections/tests/unit/gapic/beyondcorp_appconnections_v1/test_app_connections_service.py b/packages/google-cloud-beyondcorp-appconnections/tests/unit/gapic/beyondcorp_appconnections_v1/test_app_connections_service.py index 90ad61c89371..94266beb90a2 100644 --- a/packages/google-cloud-beyondcorp-appconnections/tests/unit/gapic/beyondcorp_appconnections_v1/test_app_connections_service.py +++ b/packages/google-cloud-beyondcorp-appconnections/tests/unit/gapic/beyondcorp_appconnections_v1/test_app_connections_service.py @@ -352,94 +352,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AppConnectionsServiceClient, - transports.AppConnectionsServiceGrpcTransport, - "grpc", - ), - ( - AppConnectionsServiceClient, - transports.AppConnectionsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md b/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md index 0d279593f877..2eb8e5d3c6f8 100644 --- a/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appconnectors-v0.4.12...google-cloud-beyondcorp-appconnectors-v0.4.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.4.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appconnectors-v0.4.11...google-cloud-beyondcorp-appconnectors-v0.4.12) (2024-10-24) diff --git a/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors/gapic_version.py b/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors/gapic_version.py +++ b/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors_v1/gapic_version.py b/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors_v1/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors_v1/gapic_version.py +++ b/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors_v1/services/app_connectors_service/client.py b/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors_v1/services/app_connectors_service/client.py index a73843d7ad5b..58ab8fef2955 100644 --- a/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors_v1/services/app_connectors_service/client.py +++ b/packages/google-cloud-beyondcorp-appconnectors/google/cloud/beyondcorp_appconnectors_v1/services/app_connectors_service/client.py @@ -491,36 +491,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AppConnectorsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -530,13 +500,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AppConnectorsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-beyondcorp-appconnectors/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appconnectors.v1.json b/packages/google-cloud-beyondcorp-appconnectors/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appconnectors.v1.json index f55f3a60f358..4c4360126238 100644 --- a/packages/google-cloud-beyondcorp-appconnectors/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appconnectors.v1.json +++ b/packages/google-cloud-beyondcorp-appconnectors/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appconnectors.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-beyondcorp-appconnectors", - "version": "0.4.12" + "version": "0.4.13" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-appconnectors/tests/unit/gapic/beyondcorp_appconnectors_v1/test_app_connectors_service.py b/packages/google-cloud-beyondcorp-appconnectors/tests/unit/gapic/beyondcorp_appconnectors_v1/test_app_connectors_service.py index 9230a4789b59..3813dd6c1eab 100644 --- a/packages/google-cloud-beyondcorp-appconnectors/tests/unit/gapic/beyondcorp_appconnectors_v1/test_app_connectors_service.py +++ b/packages/google-cloud-beyondcorp-appconnectors/tests/unit/gapic/beyondcorp_appconnectors_v1/test_app_connectors_service.py @@ -355,94 +355,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AppConnectorsServiceClient, - transports.AppConnectorsServiceGrpcTransport, - "grpc", - ), - ( - AppConnectorsServiceClient, - transports.AppConnectorsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md b/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md index 8383a6f906e9..f75afc01d50c 100644 --- a/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appgateways-v0.4.12...google-cloud-beyondcorp-appgateways-v0.4.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.4.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appgateways-v0.4.11...google-cloud-beyondcorp-appgateways-v0.4.12) (2024-10-24) diff --git a/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways/gapic_version.py b/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways/gapic_version.py +++ b/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways_v1/gapic_version.py b/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways_v1/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways_v1/gapic_version.py +++ b/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways_v1/services/app_gateways_service/client.py b/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways_v1/services/app_gateways_service/client.py index 4070c7174fdf..8b20ee88a3b8 100644 --- a/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways_v1/services/app_gateways_service/client.py +++ b/packages/google-cloud-beyondcorp-appgateways/google/cloud/beyondcorp_appgateways_v1/services/app_gateways_service/client.py @@ -486,36 +486,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AppGatewaysServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -525,13 +495,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AppGatewaysServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-beyondcorp-appgateways/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appgateways.v1.json b/packages/google-cloud-beyondcorp-appgateways/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appgateways.v1.json index b9984c755b2a..ed4543c0a53d 100644 --- a/packages/google-cloud-beyondcorp-appgateways/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appgateways.v1.json +++ b/packages/google-cloud-beyondcorp-appgateways/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.appgateways.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-beyondcorp-appgateways", - "version": "0.4.12" + "version": "0.4.13" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-appgateways/tests/unit/gapic/beyondcorp_appgateways_v1/test_app_gateways_service.py b/packages/google-cloud-beyondcorp-appgateways/tests/unit/gapic/beyondcorp_appgateways_v1/test_app_gateways_service.py index 5b3b7a0ea869..f115c48d43da 100644 --- a/packages/google-cloud-beyondcorp-appgateways/tests/unit/gapic/beyondcorp_appgateways_v1/test_app_gateways_service.py +++ b/packages/google-cloud-beyondcorp-appgateways/tests/unit/gapic/beyondcorp_appgateways_v1/test_app_gateways_service.py @@ -347,86 +347,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AppGatewaysServiceClient, transports.AppGatewaysServiceGrpcTransport, "grpc"), - (AppGatewaysServiceClient, transports.AppGatewaysServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md b/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md index aa8f89d52ac1..415c0a74fa10 100644 --- a/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-clientconnectorservices-v0.4.12...google-cloud-beyondcorp-clientconnectorservices-v0.4.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.4.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-clientconnectorservices-v0.4.11...google-cloud-beyondcorp-clientconnectorservices-v0.4.12) (2024-10-24) diff --git a/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices/gapic_version.py b/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices/gapic_version.py +++ b/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices_v1/gapic_version.py b/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices_v1/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices_v1/gapic_version.py +++ b/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices_v1/services/client_connector_services_service/client.py b/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices_v1/services/client_connector_services_service/client.py index 1debb047061f..b84831bdbecf 100644 --- a/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices_v1/services/client_connector_services_service/client.py +++ b/packages/google-cloud-beyondcorp-clientconnectorservices/google/cloud/beyondcorp_clientconnectorservices_v1/services/client_connector_services_service/client.py @@ -497,36 +497,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ClientConnectorServicesServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -536,13 +506,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ClientConnectorServicesServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-beyondcorp-clientconnectorservices/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.clientconnectorservices.v1.json b/packages/google-cloud-beyondcorp-clientconnectorservices/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.clientconnectorservices.v1.json index d68ab0ef1ce6..eaf0d4846226 100644 --- a/packages/google-cloud-beyondcorp-clientconnectorservices/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.clientconnectorservices.v1.json +++ b/packages/google-cloud-beyondcorp-clientconnectorservices/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.clientconnectorservices.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-beyondcorp-clientconnectorservices", - "version": "0.4.12" + "version": "0.4.13" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-clientconnectorservices/tests/unit/gapic/beyondcorp_clientconnectorservices_v1/test_client_connector_services_service.py b/packages/google-cloud-beyondcorp-clientconnectorservices/tests/unit/gapic/beyondcorp_clientconnectorservices_v1/test_client_connector_services_service.py index 49ebbb7654f9..dbef79a4e165 100644 --- a/packages/google-cloud-beyondcorp-clientconnectorservices/tests/unit/gapic/beyondcorp_clientconnectorservices_v1/test_client_connector_services_service.py +++ b/packages/google-cloud-beyondcorp-clientconnectorservices/tests/unit/gapic/beyondcorp_clientconnectorservices_v1/test_client_connector_services_service.py @@ -369,94 +369,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ClientConnectorServicesServiceClient, - transports.ClientConnectorServicesServiceGrpcTransport, - "grpc", - ), - ( - ClientConnectorServicesServiceClient, - transports.ClientConnectorServicesServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md b/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md index c29dffc58180..7508f6c3d258 100644 --- a/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-clientgateways-v0.4.11...google-cloud-beyondcorp-clientgateways-v0.4.12) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.4.11](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-clientgateways-v0.4.10...google-cloud-beyondcorp-clientgateways-v0.4.11) (2024-10-24) diff --git a/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways/gapic_version.py b/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways/gapic_version.py index 5feceb32bedf..db2ef16a95a4 100644 --- a/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways/gapic_version.py +++ b/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.11" # {x-release-please-version} +__version__ = "0.4.12" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways_v1/gapic_version.py b/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways_v1/gapic_version.py index 5feceb32bedf..db2ef16a95a4 100644 --- a/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways_v1/gapic_version.py +++ b/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.11" # {x-release-please-version} +__version__ = "0.4.12" # {x-release-please-version} diff --git a/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways_v1/services/client_gateways_service/client.py b/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways_v1/services/client_gateways_service/client.py index a0ecd8a65ae9..32db262535ce 100644 --- a/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways_v1/services/client_gateways_service/client.py +++ b/packages/google-cloud-beyondcorp-clientgateways/google/cloud/beyondcorp_clientgateways_v1/services/client_gateways_service/client.py @@ -485,36 +485,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ClientGatewaysServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -524,13 +494,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ClientGatewaysServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-beyondcorp-clientgateways/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.clientgateways.v1.json b/packages/google-cloud-beyondcorp-clientgateways/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.clientgateways.v1.json index 48690602b31c..477a6153540f 100644 --- a/packages/google-cloud-beyondcorp-clientgateways/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.clientgateways.v1.json +++ b/packages/google-cloud-beyondcorp-clientgateways/samples/generated_samples/snippet_metadata_google.cloud.beyondcorp.clientgateways.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-beyondcorp-clientgateways", - "version": "0.4.11" + "version": "0.4.12" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-clientgateways/tests/unit/gapic/beyondcorp_clientgateways_v1/test_client_gateways_service.py b/packages/google-cloud-beyondcorp-clientgateways/tests/unit/gapic/beyondcorp_clientgateways_v1/test_client_gateways_service.py index 790708a76e0d..269a04e975e5 100644 --- a/packages/google-cloud-beyondcorp-clientgateways/tests/unit/gapic/beyondcorp_clientgateways_v1/test_client_gateways_service.py +++ b/packages/google-cloud-beyondcorp-clientgateways/tests/unit/gapic/beyondcorp_clientgateways_v1/test_client_gateways_service.py @@ -351,94 +351,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ClientGatewaysServiceClient, - transports.ClientGatewaysServiceGrpcTransport, - "grpc", - ), - ( - ClientGatewaysServiceClient, - transports.ClientGatewaysServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md b/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md index 9046e5e4b3da..023f68511fc5 100644 --- a/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md +++ b/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-analyticshub-v0.4.12...google-cloud-bigquery-analyticshub-v0.4.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.4.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-analyticshub-v0.4.11...google-cloud-bigquery-analyticshub-v0.4.12) (2024-10-24) diff --git a/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub/gapic_version.py b/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub/gapic_version.py +++ b/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub_v1/gapic_version.py b/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub_v1/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub_v1/gapic_version.py +++ b/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub_v1/services/analytics_hub_service/client.py b/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub_v1/services/analytics_hub_service/client.py index c9dabbcb36ef..3d2fd8b3bbe1 100644 --- a/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub_v1/services/analytics_hub_service/client.py +++ b/packages/google-cloud-bigquery-analyticshub/google/cloud/bigquery_analyticshub_v1/services/analytics_hub_service/client.py @@ -560,36 +560,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AnalyticsHubServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -599,13 +569,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AnalyticsHubServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-analyticshub/samples/generated_samples/snippet_metadata_google.cloud.bigquery.analyticshub.v1.json b/packages/google-cloud-bigquery-analyticshub/samples/generated_samples/snippet_metadata_google.cloud.bigquery.analyticshub.v1.json index ea627028f61e..37e294320dde 100644 --- a/packages/google-cloud-bigquery-analyticshub/samples/generated_samples/snippet_metadata_google.cloud.bigquery.analyticshub.v1.json +++ b/packages/google-cloud-bigquery-analyticshub/samples/generated_samples/snippet_metadata_google.cloud.bigquery.analyticshub.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-analyticshub", - "version": "0.4.12" + "version": "0.4.13" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-analyticshub/tests/unit/gapic/bigquery_analyticshub_v1/test_analytics_hub_service.py b/packages/google-cloud-bigquery-analyticshub/tests/unit/gapic/bigquery_analyticshub_v1/test_analytics_hub_service.py index 4675dc9d6199..98c4565af87b 100644 --- a/packages/google-cloud-bigquery-analyticshub/tests/unit/gapic/bigquery_analyticshub_v1/test_analytics_hub_service.py +++ b/packages/google-cloud-bigquery-analyticshub/tests/unit/gapic/bigquery_analyticshub_v1/test_analytics_hub_service.py @@ -346,89 +346,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AnalyticsHubServiceClient, - transports.AnalyticsHubServiceGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-biglake/CHANGELOG.md b/packages/google-cloud-bigquery-biglake/CHANGELOG.md index 5da23095f8f3..a9c29575f39d 100644 --- a/packages/google-cloud-bigquery-biglake/CHANGELOG.md +++ b/packages/google-cloud-bigquery-biglake/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.11](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-biglake-v0.4.10...google-cloud-bigquery-biglake-v0.4.11) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.4.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-biglake-v0.4.9...google-cloud-bigquery-biglake-v0.4.10) (2024-10-24) diff --git a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake/gapic_version.py b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake/gapic_version.py index 792f80c59ee5..5feceb32bedf 100644 --- a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake/gapic_version.py +++ b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.10" # {x-release-please-version} +__version__ = "0.4.11" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1/gapic_version.py b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1/gapic_version.py index 792f80c59ee5..5feceb32bedf 100644 --- a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1/gapic_version.py +++ b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.10" # {x-release-please-version} +__version__ = "0.4.11" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1/services/metastore_service/client.py b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1/services/metastore_service/client.py index 37fc63db909f..fa45ceafe1e3 100644 --- a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1/services/metastore_service/client.py +++ b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1/services/metastore_service/client.py @@ -525,36 +525,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = MetastoreServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -564,13 +534,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or MetastoreServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1alpha1/gapic_version.py b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1alpha1/gapic_version.py index 792f80c59ee5..5feceb32bedf 100644 --- a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1alpha1/gapic_version.py +++ b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.10" # {x-release-please-version} +__version__ = "0.4.11" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1alpha1/services/metastore_service/client.py b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1alpha1/services/metastore_service/client.py index 0893a12db218..74e3fad5eb61 100644 --- a/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1alpha1/services/metastore_service/client.py +++ b/packages/google-cloud-bigquery-biglake/google/cloud/bigquery_biglake_v1alpha1/services/metastore_service/client.py @@ -551,36 +551,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = MetastoreServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -590,13 +560,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or MetastoreServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-biglake/samples/generated_samples/snippet_metadata_google.cloud.bigquery.biglake.v1.json b/packages/google-cloud-bigquery-biglake/samples/generated_samples/snippet_metadata_google.cloud.bigquery.biglake.v1.json index 75f95af4287d..a32c80dfc1c9 100644 --- a/packages/google-cloud-bigquery-biglake/samples/generated_samples/snippet_metadata_google.cloud.bigquery.biglake.v1.json +++ b/packages/google-cloud-bigquery-biglake/samples/generated_samples/snippet_metadata_google.cloud.bigquery.biglake.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-biglake", - "version": "0.4.10" + "version": "0.4.11" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-biglake/samples/generated_samples/snippet_metadata_google.cloud.bigquery.biglake.v1alpha1.json b/packages/google-cloud-bigquery-biglake/samples/generated_samples/snippet_metadata_google.cloud.bigquery.biglake.v1alpha1.json index f256ed3c2b14..9125bc437013 100644 --- a/packages/google-cloud-bigquery-biglake/samples/generated_samples/snippet_metadata_google.cloud.bigquery.biglake.v1alpha1.json +++ b/packages/google-cloud-bigquery-biglake/samples/generated_samples/snippet_metadata_google.cloud.bigquery.biglake.v1alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-biglake", - "version": "0.4.10" + "version": "0.4.11" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-biglake/tests/unit/gapic/bigquery_biglake_v1/test_metastore_service.py b/packages/google-cloud-bigquery-biglake/tests/unit/gapic/bigquery_biglake_v1/test_metastore_service.py index ea0bf42d68c1..75a521c0a1f1 100644 --- a/packages/google-cloud-bigquery-biglake/tests/unit/gapic/bigquery_biglake_v1/test_metastore_service.py +++ b/packages/google-cloud-bigquery-biglake/tests/unit/gapic/bigquery_biglake_v1/test_metastore_service.py @@ -321,86 +321,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (MetastoreServiceClient, transports.MetastoreServiceGrpcTransport, "grpc"), - (MetastoreServiceClient, transports.MetastoreServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-biglake/tests/unit/gapic/bigquery_biglake_v1alpha1/test_metastore_service.py b/packages/google-cloud-bigquery-biglake/tests/unit/gapic/bigquery_biglake_v1alpha1/test_metastore_service.py index d8b7a6b4cae9..68237c0ee58a 100644 --- a/packages/google-cloud-bigquery-biglake/tests/unit/gapic/bigquery_biglake_v1alpha1/test_metastore_service.py +++ b/packages/google-cloud-bigquery-biglake/tests/unit/gapic/bigquery_biglake_v1alpha1/test_metastore_service.py @@ -321,86 +321,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (MetastoreServiceClient, transports.MetastoreServiceGrpcTransport, "grpc"), - (MetastoreServiceClient, transports.MetastoreServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-connection/CHANGELOG.md b/packages/google-cloud-bigquery-connection/CHANGELOG.md index ef0061729ec2..11e3020d1ffa 100644 --- a/packages/google-cloud-bigquery-connection/CHANGELOG.md +++ b/packages/google-cloud-bigquery-connection/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.16.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-connection-v1.16.0...google-cloud-bigquery-connection-v1.16.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [1.16.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-connection-v1.15.5...google-cloud-bigquery-connection-v1.16.0) (2024-10-24) diff --git a/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection/gapic_version.py b/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection/gapic_version.py index 3e0ea3b28f0a..b6e92d4eebd5 100644 --- a/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection/gapic_version.py +++ b/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.0" # {x-release-please-version} +__version__ = "1.16.1" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection_v1/gapic_version.py b/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection_v1/gapic_version.py index 3e0ea3b28f0a..b6e92d4eebd5 100644 --- a/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection_v1/gapic_version.py +++ b/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.0" # {x-release-please-version} +__version__ = "1.16.1" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection_v1/services/connection_service/client.py b/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection_v1/services/connection_service/client.py index 4dd767c16bad..f13986e90deb 100644 --- a/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection_v1/services/connection_service/client.py +++ b/packages/google-cloud-bigquery-connection/google/cloud/bigquery_connection_v1/services/connection_service/client.py @@ -512,36 +512,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConnectionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -551,13 +521,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ConnectionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-connection/samples/generated_samples/snippet_metadata_google.cloud.bigquery.connection.v1.json b/packages/google-cloud-bigquery-connection/samples/generated_samples/snippet_metadata_google.cloud.bigquery.connection.v1.json index 4059428c848c..b942d3e38505 100644 --- a/packages/google-cloud-bigquery-connection/samples/generated_samples/snippet_metadata_google.cloud.bigquery.connection.v1.json +++ b/packages/google-cloud-bigquery-connection/samples/generated_samples/snippet_metadata_google.cloud.bigquery.connection.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-connection", - "version": "1.16.0" + "version": "1.16.1" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-connection/tests/unit/gapic/bigquery_connection_v1/test_connection_service.py b/packages/google-cloud-bigquery-connection/tests/unit/gapic/bigquery_connection_v1/test_connection_service.py index 5053176e8d49..b5db651971ac 100644 --- a/packages/google-cloud-bigquery-connection/tests/unit/gapic/bigquery_connection_v1/test_connection_service.py +++ b/packages/google-cloud-bigquery-connection/tests/unit/gapic/bigquery_connection_v1/test_connection_service.py @@ -333,86 +333,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ConnectionServiceClient, transports.ConnectionServiceGrpcTransport, "grpc"), - (ConnectionServiceClient, transports.ConnectionServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md b/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md index ae9f995cb028..90ba2ac069a0 100644 --- a/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md +++ b/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.15](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-data-exchange-v0.5.14...google-cloud-bigquery-data-exchange-v0.5.15) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.5.14](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-data-exchange-v0.5.13...google-cloud-bigquery-data-exchange-v0.5.14) (2024-10-24) diff --git a/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange/gapic_version.py b/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange/gapic_version.py index 0f3dcb10f73a..35c9af734238 100644 --- a/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange/gapic_version.py +++ b/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.14" # {x-release-please-version} +__version__ = "0.5.15" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange_v1beta1/gapic_version.py b/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange_v1beta1/gapic_version.py index 0f3dcb10f73a..35c9af734238 100644 --- a/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange_v1beta1/gapic_version.py +++ b/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.14" # {x-release-please-version} +__version__ = "0.5.15" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange_v1beta1/services/analytics_hub_service/client.py b/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange_v1beta1/services/analytics_hub_service/client.py index 83295d49161c..a51abb3756e4 100644 --- a/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange_v1beta1/services/analytics_hub_service/client.py +++ b/packages/google-cloud-bigquery-data-exchange/google/cloud/bigquery_data_exchange_v1beta1/services/analytics_hub_service/client.py @@ -514,36 +514,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AnalyticsHubServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -553,13 +523,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AnalyticsHubServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-data-exchange/samples/generated_samples/snippet_metadata_google.cloud.bigquery.dataexchange.v1beta1.json b/packages/google-cloud-bigquery-data-exchange/samples/generated_samples/snippet_metadata_google.cloud.bigquery.dataexchange.v1beta1.json index b60d6300e315..622338e9867c 100644 --- a/packages/google-cloud-bigquery-data-exchange/samples/generated_samples/snippet_metadata_google.cloud.bigquery.dataexchange.v1beta1.json +++ b/packages/google-cloud-bigquery-data-exchange/samples/generated_samples/snippet_metadata_google.cloud.bigquery.dataexchange.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-data-exchange", - "version": "0.5.14" + "version": "0.5.15" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-data-exchange/tests/unit/gapic/bigquery_data_exchange_v1beta1/test_analytics_hub_service.py b/packages/google-cloud-bigquery-data-exchange/tests/unit/gapic/bigquery_data_exchange_v1beta1/test_analytics_hub_service.py index 175370abe5c4..2840816a64cc 100644 --- a/packages/google-cloud-bigquery-data-exchange/tests/unit/gapic/bigquery_data_exchange_v1beta1/test_analytics_hub_service.py +++ b/packages/google-cloud-bigquery-data-exchange/tests/unit/gapic/bigquery_data_exchange_v1beta1/test_analytics_hub_service.py @@ -335,89 +335,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AnalyticsHubServiceClient, - transports.AnalyticsHubServiceGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md b/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md index 3835827d04f6..e6a496e2ec18 100644 --- a/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md +++ b/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.6.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-datapolicies-v0.6.9...google-cloud-bigquery-datapolicies-v0.6.10) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.6.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-datapolicies-v0.6.8...google-cloud-bigquery-datapolicies-v0.6.9) (2024-10-24) diff --git a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies/gapic_version.py b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies/gapic_version.py index 1699c98da708..8ebdaa033b52 100644 --- a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies/gapic_version.py +++ b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.9" # {x-release-please-version} +__version__ = "0.6.10" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1/gapic_version.py b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1/gapic_version.py index 1699c98da708..8ebdaa033b52 100644 --- a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1/gapic_version.py +++ b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.9" # {x-release-please-version} +__version__ = "0.6.10" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1/services/data_policy_service/client.py b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1/services/data_policy_service/client.py index 50a82cf1652f..33d22df0b8b4 100644 --- a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1/services/data_policy_service/client.py +++ b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1/services/data_policy_service/client.py @@ -469,36 +469,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataPolicyServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -508,13 +478,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataPolicyServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1beta1/gapic_version.py b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1beta1/gapic_version.py index 1699c98da708..8ebdaa033b52 100644 --- a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1beta1/gapic_version.py +++ b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.9" # {x-release-please-version} +__version__ = "0.6.10" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1beta1/services/data_policy_service/client.py b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1beta1/services/data_policy_service/client.py index c7e5e6aa27a8..a71fefd1fcc2 100644 --- a/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1beta1/services/data_policy_service/client.py +++ b/packages/google-cloud-bigquery-datapolicies/google/cloud/bigquery_datapolicies_v1beta1/services/data_policy_service/client.py @@ -469,36 +469,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataPolicyServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -508,13 +478,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataPolicyServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-datapolicies/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datapolicies.v1.json b/packages/google-cloud-bigquery-datapolicies/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datapolicies.v1.json index 7a4fc23b1f0f..5dba0dd52f72 100644 --- a/packages/google-cloud-bigquery-datapolicies/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datapolicies.v1.json +++ b/packages/google-cloud-bigquery-datapolicies/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datapolicies.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-datapolicies", - "version": "0.6.9" + "version": "0.6.10" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-datapolicies/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datapolicies.v1beta1.json b/packages/google-cloud-bigquery-datapolicies/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datapolicies.v1beta1.json index 83ef5aa3e557..f1f0fc45f50f 100644 --- a/packages/google-cloud-bigquery-datapolicies/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datapolicies.v1beta1.json +++ b/packages/google-cloud-bigquery-datapolicies/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datapolicies.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-datapolicies", - "version": "0.6.9" + "version": "0.6.10" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-datapolicies/tests/unit/gapic/bigquery_datapolicies_v1/test_data_policy_service.py b/packages/google-cloud-bigquery-datapolicies/tests/unit/gapic/bigquery_datapolicies_v1/test_data_policy_service.py index 230d94d95a7b..289587bb321e 100644 --- a/packages/google-cloud-bigquery-datapolicies/tests/unit/gapic/bigquery_datapolicies_v1/test_data_policy_service.py +++ b/packages/google-cloud-bigquery-datapolicies/tests/unit/gapic/bigquery_datapolicies_v1/test_data_policy_service.py @@ -332,86 +332,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DataPolicyServiceClient, transports.DataPolicyServiceGrpcTransport, "grpc"), - (DataPolicyServiceClient, transports.DataPolicyServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-datapolicies/tests/unit/gapic/bigquery_datapolicies_v1beta1/test_data_policy_service.py b/packages/google-cloud-bigquery-datapolicies/tests/unit/gapic/bigquery_datapolicies_v1beta1/test_data_policy_service.py index 284607a51c22..a9ac78315857 100644 --- a/packages/google-cloud-bigquery-datapolicies/tests/unit/gapic/bigquery_datapolicies_v1beta1/test_data_policy_service.py +++ b/packages/google-cloud-bigquery-datapolicies/tests/unit/gapic/bigquery_datapolicies_v1beta1/test_data_policy_service.py @@ -327,85 +327,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DataPolicyServiceClient, transports.DataPolicyServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md b/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md index dc98246fb117..7582709490c5 100644 --- a/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md +++ b/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-bigquery-datatransfer/#history +## [3.17.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-datatransfer-v3.17.0...google-cloud-bigquery-datatransfer-v3.17.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [3.17.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-datatransfer-v3.16.0...google-cloud-bigquery-datatransfer-v3.17.0) (2024-10-24) diff --git a/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer/gapic_version.py b/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer/gapic_version.py index d2b82f793e78..6942500960db 100644 --- a/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer/gapic_version.py +++ b/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.17.0" # {x-release-please-version} +__version__ = "3.17.1" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer_v1/gapic_version.py b/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer_v1/gapic_version.py index d2b82f793e78..6942500960db 100644 --- a/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer_v1/gapic_version.py +++ b/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.17.0" # {x-release-please-version} +__version__ = "3.17.1" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py b/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py index 15df58ebffa6..3f6bf741deed 100644 --- a/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py +++ b/packages/google-cloud-bigquery-datatransfer/google/cloud/bigquery_datatransfer_v1/services/data_transfer_service/client.py @@ -509,36 +509,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataTransferServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -548,13 +518,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataTransferServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-datatransfer/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datatransfer.v1.json b/packages/google-cloud-bigquery-datatransfer/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datatransfer.v1.json index d731f68dc184..fb91bc666764 100644 --- a/packages/google-cloud-bigquery-datatransfer/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datatransfer.v1.json +++ b/packages/google-cloud-bigquery-datatransfer/samples/generated_samples/snippet_metadata_google.cloud.bigquery.datatransfer.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-datatransfer", - "version": "3.17.0" + "version": "3.17.1" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-datatransfer/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py b/packages/google-cloud-bigquery-datatransfer/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py index 705721cba2ba..48c9b73e15b0 100644 --- a/packages/google-cloud-bigquery-datatransfer/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py +++ b/packages/google-cloud-bigquery-datatransfer/tests/unit/gapic/bigquery_datatransfer_v1/test_data_transfer_service.py @@ -341,94 +341,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - DataTransferServiceClient, - transports.DataTransferServiceGrpcTransport, - "grpc", - ), - ( - DataTransferServiceClient, - transports.DataTransferServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-migration/CHANGELOG.md b/packages/google-cloud-bigquery-migration/CHANGELOG.md index 883dd9e7712a..f860496f6900 100644 --- a/packages/google-cloud-bigquery-migration/CHANGELOG.md +++ b/packages/google-cloud-bigquery-migration/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.11.11](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-migration-v0.11.10...google-cloud-bigquery-migration-v0.11.11) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [0.11.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-migration-v0.11.9...google-cloud-bigquery-migration-v0.11.10) (2024-10-24) diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration/gapic_version.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration/gapic_version.py index 8914d3106fe9..11e34cec2824 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration/gapic_version.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.10" # {x-release-please-version} +__version__ = "0.11.11" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/gapic_version.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/gapic_version.py index 8914d3106fe9..11e34cec2824 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/gapic_version.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.10" # {x-release-please-version} +__version__ = "0.11.11" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/services/migration_service/client.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/services/migration_service/client.py index 87b6df7fd5f2..0db4106dafbf 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/services/migration_service/client.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2/services/migration_service/client.py @@ -491,36 +491,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = MigrationServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -530,13 +500,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or MigrationServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/gapic_version.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/gapic_version.py index 8914d3106fe9..11e34cec2824 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/gapic_version.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.10" # {x-release-please-version} +__version__ = "0.11.11" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/services/migration_service/client.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/services/migration_service/client.py index 32164e645021..5a2c7a340e99 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/services/migration_service/client.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/services/migration_service/client.py @@ -491,36 +491,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = MigrationServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -530,13 +500,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or MigrationServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/services/sql_translation_service/client.py b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/services/sql_translation_service/client.py index ff48b7f2af4b..54c1064a5a02 100644 --- a/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/services/sql_translation_service/client.py +++ b/packages/google-cloud-bigquery-migration/google/cloud/bigquery_migration_v2alpha/services/sql_translation_service/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SqlTranslationServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SqlTranslationServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-migration/samples/generated_samples/snippet_metadata_google.cloud.bigquery.migration.v2.json b/packages/google-cloud-bigquery-migration/samples/generated_samples/snippet_metadata_google.cloud.bigquery.migration.v2.json index bfe515847079..53768f71bcd4 100644 --- a/packages/google-cloud-bigquery-migration/samples/generated_samples/snippet_metadata_google.cloud.bigquery.migration.v2.json +++ b/packages/google-cloud-bigquery-migration/samples/generated_samples/snippet_metadata_google.cloud.bigquery.migration.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-migration", - "version": "0.11.10" + "version": "0.11.11" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-migration/samples/generated_samples/snippet_metadata_google.cloud.bigquery.migration.v2alpha.json b/packages/google-cloud-bigquery-migration/samples/generated_samples/snippet_metadata_google.cloud.bigquery.migration.v2alpha.json index c9c8e2f64bce..e6977344f9bb 100644 --- a/packages/google-cloud-bigquery-migration/samples/generated_samples/snippet_metadata_google.cloud.bigquery.migration.v2alpha.json +++ b/packages/google-cloud-bigquery-migration/samples/generated_samples/snippet_metadata_google.cloud.bigquery.migration.v2alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-migration", - "version": "0.11.10" + "version": "0.11.11" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2/test_migration_service.py b/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2/test_migration_service.py index 70ab3e7828b3..52e18ce616db 100644 --- a/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2/test_migration_service.py +++ b/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2/test_migration_service.py @@ -328,85 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (MigrationServiceClient, transports.MigrationServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2alpha/test_migration_service.py b/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2alpha/test_migration_service.py index 1d2d709e5364..ec6917df7b1c 100644 --- a/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2alpha/test_migration_service.py +++ b/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2alpha/test_migration_service.py @@ -325,85 +325,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (MigrationServiceClient, transports.MigrationServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2alpha/test_sql_translation_service.py b/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2alpha/test_sql_translation_service.py index 5301798ce0ce..b4d046a3b632 100644 --- a/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2alpha/test_sql_translation_service.py +++ b/packages/google-cloud-bigquery-migration/tests/unit/gapic/bigquery_migration_v2alpha/test_sql_translation_service.py @@ -329,89 +329,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - SqlTranslationServiceClient, - transports.SqlTranslationServiceGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-bigquery-reservation/CHANGELOG.md b/packages/google-cloud-bigquery-reservation/CHANGELOG.md index b3fa55e51add..463f17384501 100644 --- a/packages/google-cloud-bigquery-reservation/CHANGELOG.md +++ b/packages/google-cloud-bigquery-reservation/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.14.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-reservation-v1.14.0...google-cloud-bigquery-reservation-v1.14.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [1.14.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-reservation-v1.13.5...google-cloud-bigquery-reservation-v1.14.0) (2024-10-24) diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation/gapic_version.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation/gapic_version.py index 2159c8af6f8e..231f5cf041ff 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation/gapic_version.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.0" # {x-release-please-version} +__version__ = "1.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/gapic_version.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/gapic_version.py index 2159c8af6f8e..231f5cf041ff 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/gapic_version.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.0" # {x-release-please-version} +__version__ = "1.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py index 30e6b9de73dd..d23e2c9f8879 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py @@ -550,36 +550,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ReservationServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -589,13 +559,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ReservationServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-bigquery-reservation/samples/generated_samples/snippet_metadata_google.cloud.bigquery.reservation.v1.json b/packages/google-cloud-bigquery-reservation/samples/generated_samples/snippet_metadata_google.cloud.bigquery.reservation.v1.json index c78b07a08ba9..c3418e392fa3 100644 --- a/packages/google-cloud-bigquery-reservation/samples/generated_samples/snippet_metadata_google.cloud.bigquery.reservation.v1.json +++ b/packages/google-cloud-bigquery-reservation/samples/generated_samples/snippet_metadata_google.cloud.bigquery.reservation.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-bigquery-reservation", - "version": "1.14.0" + "version": "1.14.1" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-reservation/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py b/packages/google-cloud-bigquery-reservation/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py index 136210005cb9..63c6e54d04e3 100644 --- a/packages/google-cloud-bigquery-reservation/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py +++ b/packages/google-cloud-bigquery-reservation/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py @@ -336,86 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ReservationServiceClient, transports.ReservationServiceGrpcTransport, "grpc"), - (ReservationServiceClient, transports.ReservationServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-billing-budgets/CHANGELOG.md b/packages/google-cloud-billing-budgets/CHANGELOG.md index 6e6f8814c459..871b40c862b9 100644 --- a/packages/google-cloud-billing-budgets/CHANGELOG.md +++ b/packages/google-cloud-billing-budgets/CHANGELOG.md @@ -1,4 +1,11 @@ # Changelog +## [1.15.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-billing-budgets-v1.15.0...google-cloud-billing-budgets-v1.15.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [1.15.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-billing-budgets-v1.14.5...google-cloud-billing-budgets-v1.15.0) (2024-10-24) diff --git a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets/gapic_version.py b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets/gapic_version.py index cf18a472a8a2..2fd2bb1630b4 100644 --- a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets/gapic_version.py +++ b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.15.0" # {x-release-please-version} +__version__ = "1.15.1" # {x-release-please-version} diff --git a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1/gapic_version.py b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1/gapic_version.py index cf18a472a8a2..2fd2bb1630b4 100644 --- a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1/gapic_version.py +++ b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.15.0" # {x-release-please-version} +__version__ = "1.15.1" # {x-release-please-version} diff --git a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1/services/budget_service/client.py b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1/services/budget_service/client.py index 2095fbefdf66..a87f5383108a 100644 --- a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1/services/budget_service/client.py +++ b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1/services/budget_service/client.py @@ -461,36 +461,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BudgetServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -500,13 +470,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BudgetServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1beta1/gapic_version.py b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1beta1/gapic_version.py index cf18a472a8a2..2fd2bb1630b4 100644 --- a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1beta1/gapic_version.py +++ b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.15.0" # {x-release-please-version} +__version__ = "1.15.1" # {x-release-please-version} diff --git a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1beta1/services/budget_service/client.py b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1beta1/services/budget_service/client.py index 8407b63a3c79..40d7aa259418 100644 --- a/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1beta1/services/budget_service/client.py +++ b/packages/google-cloud-billing-budgets/google/cloud/billing/budgets_v1beta1/services/budget_service/client.py @@ -457,36 +457,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BudgetServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -496,13 +466,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BudgetServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-billing-budgets/samples/generated_samples/snippet_metadata_google.cloud.billing.budgets.v1.json b/packages/google-cloud-billing-budgets/samples/generated_samples/snippet_metadata_google.cloud.billing.budgets.v1.json index cdc6ceff3922..c53756bde983 100644 --- a/packages/google-cloud-billing-budgets/samples/generated_samples/snippet_metadata_google.cloud.billing.budgets.v1.json +++ b/packages/google-cloud-billing-budgets/samples/generated_samples/snippet_metadata_google.cloud.billing.budgets.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-billing-budgets", - "version": "1.15.0" + "version": "1.15.1" }, "snippets": [ { diff --git a/packages/google-cloud-billing-budgets/samples/generated_samples/snippet_metadata_google.cloud.billing.budgets.v1beta1.json b/packages/google-cloud-billing-budgets/samples/generated_samples/snippet_metadata_google.cloud.billing.budgets.v1beta1.json index 1437a9f2095d..a3d3721a6a97 100644 --- a/packages/google-cloud-billing-budgets/samples/generated_samples/snippet_metadata_google.cloud.billing.budgets.v1beta1.json +++ b/packages/google-cloud-billing-budgets/samples/generated_samples/snippet_metadata_google.cloud.billing.budgets.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-billing-budgets", - "version": "1.15.0" + "version": "1.15.1" }, "snippets": [ { diff --git a/packages/google-cloud-billing-budgets/tests/unit/gapic/budgets_v1/test_budget_service.py b/packages/google-cloud-billing-budgets/tests/unit/gapic/budgets_v1/test_budget_service.py index a1a7f146bd54..0e2ce042a50f 100644 --- a/packages/google-cloud-billing-budgets/tests/unit/gapic/budgets_v1/test_budget_service.py +++ b/packages/google-cloud-billing-budgets/tests/unit/gapic/budgets_v1/test_budget_service.py @@ -318,86 +318,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BudgetServiceClient, transports.BudgetServiceGrpcTransport, "grpc"), - (BudgetServiceClient, transports.BudgetServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-billing-budgets/tests/unit/gapic/budgets_v1beta1/test_budget_service.py b/packages/google-cloud-billing-budgets/tests/unit/gapic/budgets_v1beta1/test_budget_service.py index 95b5422338cf..5b19669c64b4 100644 --- a/packages/google-cloud-billing-budgets/tests/unit/gapic/budgets_v1beta1/test_budget_service.py +++ b/packages/google-cloud-billing-budgets/tests/unit/gapic/budgets_v1beta1/test_budget_service.py @@ -313,85 +313,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BudgetServiceClient, transports.BudgetServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-billing/CHANGELOG.md b/packages/google-cloud-billing/CHANGELOG.md index c15dcc6b6eec..ba23ce3cdef0 100644 --- a/packages/google-cloud-billing/CHANGELOG.md +++ b/packages/google-cloud-billing/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.14.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-billing-v1.14.0...google-cloud-billing-v1.14.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [1.14.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-billing-v1.13.6...google-cloud-billing-v1.14.0) (2024-10-24) diff --git a/packages/google-cloud-billing/google/cloud/billing/gapic_version.py b/packages/google-cloud-billing/google/cloud/billing/gapic_version.py index 2159c8af6f8e..231f5cf041ff 100644 --- a/packages/google-cloud-billing/google/cloud/billing/gapic_version.py +++ b/packages/google-cloud-billing/google/cloud/billing/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.0" # {x-release-please-version} +__version__ = "1.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/gapic_version.py b/packages/google-cloud-billing/google/cloud/billing_v1/gapic_version.py index 2159c8af6f8e..231f5cf041ff 100644 --- a/packages/google-cloud-billing/google/cloud/billing_v1/gapic_version.py +++ b/packages/google-cloud-billing/google/cloud/billing_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.0" # {x-release-please-version} +__version__ = "1.14.1" # {x-release-please-version} diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/client.py b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/client.py index c31f665736cb..cc1f995bfa12 100644 --- a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/client.py +++ b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/client.py @@ -502,36 +502,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudBillingClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -541,13 +511,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudBillingClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/client.py b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/client.py index 864deed1c10e..60d8764dea8f 100644 --- a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/client.py +++ b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/client.py @@ -472,36 +472,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudCatalogClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -511,13 +481,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudCatalogClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-billing/samples/generated_samples/snippet_metadata_google.cloud.billing.v1.json b/packages/google-cloud-billing/samples/generated_samples/snippet_metadata_google.cloud.billing.v1.json index df7ec1193f00..fda2838313c5 100644 --- a/packages/google-cloud-billing/samples/generated_samples/snippet_metadata_google.cloud.billing.v1.json +++ b/packages/google-cloud-billing/samples/generated_samples/snippet_metadata_google.cloud.billing.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-billing", - "version": "1.14.0" + "version": "1.14.1" }, "snippets": [ { diff --git a/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_billing.py b/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_billing.py index 4d7e3bf7ae77..e46f30dba6d2 100644 --- a/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_billing.py +++ b/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_billing.py @@ -308,86 +308,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CloudBillingClient, transports.CloudBillingGrpcTransport, "grpc"), - (CloudBillingClient, transports.CloudBillingRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_catalog.py b/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_catalog.py index a4e54ccc61c2..e653309e24b8 100644 --- a/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_catalog.py +++ b/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_catalog.py @@ -304,86 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CloudCatalogClient, transports.CloudCatalogGrpcTransport, "grpc"), - (CloudCatalogClient, transports.CloudCatalogRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-binary-authorization/CHANGELOG.md b/packages/google-cloud-binary-authorization/CHANGELOG.md index 90e90fde7d93..ddaecb8ce1ed 100644 --- a/packages/google-cloud-binary-authorization/CHANGELOG.md +++ b/packages/google-cloud-binary-authorization/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-binary-authorization-v1.11.0...google-cloud-binary-authorization-v1.11.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([4ed4108](https://github.com/googleapis/google-cloud-python/commit/4ed41088ab3cbadfe4de7fa170f172666015ed24)) + ## [1.11.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-binary-authorization-v1.10.5...google-cloud-binary-authorization-v1.11.0) (2024-10-24) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization/gapic_version.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization/gapic_version.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/gapic_version.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/gapic_version.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py index 91142cfbeb1e..bdc3fbb0f4ef 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py @@ -488,36 +488,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BinauthzManagementServiceV1Client._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -527,13 +497,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BinauthzManagementServiceV1Client._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py index 592df00e4ec6..c1194731d1ea 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py @@ -455,36 +455,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SystemPolicyV1Client._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -494,13 +464,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SystemPolicyV1Client._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py index bf501c96eb59..3bbd7927dfe1 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ValidationHelperV1Client._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ValidationHelperV1Client._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/gapic_version.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/gapic_version.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py index a2e1b58e9735..9a7a80609bcc 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py @@ -491,36 +491,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BinauthzManagementServiceV1Beta1Client._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -530,13 +500,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BinauthzManagementServiceV1Beta1Client._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py index b4df4ff9e7e8..41cb4ed15afe 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py @@ -455,36 +455,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SystemPolicyV1Beta1Client._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -494,13 +464,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SystemPolicyV1Beta1Client._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-binary-authorization/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1.json b/packages/google-cloud-binary-authorization/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1.json index acf21ce3b6be..1c782ac5a11a 100644 --- a/packages/google-cloud-binary-authorization/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1.json +++ b/packages/google-cloud-binary-authorization/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-binary-authorization", - "version": "1.11.0" + "version": "1.11.1" }, "snippets": [ { diff --git a/packages/google-cloud-binary-authorization/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1beta1.json b/packages/google-cloud-binary-authorization/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1beta1.json index 481afb7cf4e2..076840734bfd 100644 --- a/packages/google-cloud-binary-authorization/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1beta1.json +++ b/packages/google-cloud-binary-authorization/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-binary-authorization", - "version": "1.11.0" + "version": "1.11.1" }, "snippets": [ { diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py index d469281e147a..dbf9b366a305 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py @@ -344,94 +344,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - BinauthzManagementServiceV1Client, - transports.BinauthzManagementServiceV1GrpcTransport, - "grpc", - ), - ( - BinauthzManagementServiceV1Client, - transports.BinauthzManagementServiceV1RestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py index f3eb91b24edb..238de5153e22 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py @@ -318,86 +318,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SystemPolicyV1Client, transports.SystemPolicyV1GrpcTransport, "grpc"), - (SystemPolicyV1Client, transports.SystemPolicyV1RestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py index 3c849bed4b50..deef7b1a5d01 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py @@ -330,86 +330,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ValidationHelperV1Client, transports.ValidationHelperV1GrpcTransport, "grpc"), - (ValidationHelperV1Client, transports.ValidationHelperV1RestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py index 286b7f65655a..69ad9bc3eb1e 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py @@ -355,94 +355,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - BinauthzManagementServiceV1Beta1Client, - transports.BinauthzManagementServiceV1Beta1GrpcTransport, - "grpc", - ), - ( - BinauthzManagementServiceV1Beta1Client, - transports.BinauthzManagementServiceV1Beta1RestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py index 4016f5595c10..a1f7defa50ae 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py @@ -333,94 +333,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - SystemPolicyV1Beta1Client, - transports.SystemPolicyV1Beta1GrpcTransport, - "grpc", - ), - ( - SystemPolicyV1Beta1Client, - transports.SystemPolicyV1Beta1RestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-certificate-manager/CHANGELOG.md b/packages/google-cloud-certificate-manager/CHANGELOG.md index 6e0c93ab449e..988dba41a365 100644 --- a/packages/google-cloud-certificate-manager/CHANGELOG.md +++ b/packages/google-cloud-certificate-manager/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.8.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-certificate-manager-v1.8.0...google-cloud-certificate-manager-v1.8.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [1.8.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-certificate-manager-v1.7.2...google-cloud-certificate-manager-v1.8.0) (2024-10-24) diff --git a/packages/google-cloud-certificate-manager/google/cloud/certificate_manager/gapic_version.py b/packages/google-cloud-certificate-manager/google/cloud/certificate_manager/gapic_version.py index 4b114d153974..02874f69f4e5 100644 --- a/packages/google-cloud-certificate-manager/google/cloud/certificate_manager/gapic_version.py +++ b/packages/google-cloud-certificate-manager/google/cloud/certificate_manager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.8.0" # {x-release-please-version} +__version__ = "1.8.1" # {x-release-please-version} diff --git a/packages/google-cloud-certificate-manager/google/cloud/certificate_manager_v1/gapic_version.py b/packages/google-cloud-certificate-manager/google/cloud/certificate_manager_v1/gapic_version.py index 4b114d153974..02874f69f4e5 100644 --- a/packages/google-cloud-certificate-manager/google/cloud/certificate_manager_v1/gapic_version.py +++ b/packages/google-cloud-certificate-manager/google/cloud/certificate_manager_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.8.0" # {x-release-please-version} +__version__ = "1.8.1" # {x-release-please-version} diff --git a/packages/google-cloud-certificate-manager/google/cloud/certificate_manager_v1/services/certificate_manager/client.py b/packages/google-cloud-certificate-manager/google/cloud/certificate_manager_v1/services/certificate_manager/client.py index 0fb3f8ee90a1..aee840ef5ff6 100644 --- a/packages/google-cloud-certificate-manager/google/cloud/certificate_manager_v1/services/certificate_manager/client.py +++ b/packages/google-cloud-certificate-manager/google/cloud/certificate_manager_v1/services/certificate_manager/client.py @@ -640,36 +640,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CertificateManagerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -679,13 +649,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CertificateManagerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-certificate-manager/samples/generated_samples/snippet_metadata_google.cloud.certificatemanager.v1.json b/packages/google-cloud-certificate-manager/samples/generated_samples/snippet_metadata_google.cloud.certificatemanager.v1.json index 89c2ca3b5ca6..913377237d4f 100644 --- a/packages/google-cloud-certificate-manager/samples/generated_samples/snippet_metadata_google.cloud.certificatemanager.v1.json +++ b/packages/google-cloud-certificate-manager/samples/generated_samples/snippet_metadata_google.cloud.certificatemanager.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-certificate-manager", - "version": "1.8.0" + "version": "1.8.1" }, "snippets": [ { diff --git a/packages/google-cloud-certificate-manager/tests/unit/gapic/certificate_manager_v1/test_certificate_manager.py b/packages/google-cloud-certificate-manager/tests/unit/gapic/certificate_manager_v1/test_certificate_manager.py index 37943cacd1dc..c674b586a135 100644 --- a/packages/google-cloud-certificate-manager/tests/unit/gapic/certificate_manager_v1/test_certificate_manager.py +++ b/packages/google-cloud-certificate-manager/tests/unit/gapic/certificate_manager_v1/test_certificate_manager.py @@ -352,86 +352,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CertificateManagerClient, transports.CertificateManagerGrpcTransport, "grpc"), - (CertificateManagerClient, transports.CertificateManagerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-channel/CHANGELOG.md b/packages/google-cloud-channel/CHANGELOG.md index 172bc3455928..06508e42eecb 100644 --- a/packages/google-cloud-channel/CHANGELOG.md +++ b/packages/google-cloud-channel/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.20.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-channel-v1.20.0...google-cloud-channel-v1.20.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [1.20.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-channel-v1.19.0...google-cloud-channel-v1.20.0) (2024-10-24) diff --git a/packages/google-cloud-channel/google/cloud/channel/gapic_version.py b/packages/google-cloud-channel/google/cloud/channel/gapic_version.py index c8ba2b4c6a4f..4da8c821edb1 100644 --- a/packages/google-cloud-channel/google/cloud/channel/gapic_version.py +++ b/packages/google-cloud-channel/google/cloud/channel/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.20.0" # {x-release-please-version} +__version__ = "1.20.1" # {x-release-please-version} diff --git a/packages/google-cloud-channel/google/cloud/channel_v1/gapic_version.py b/packages/google-cloud-channel/google/cloud/channel_v1/gapic_version.py index c8ba2b4c6a4f..4da8c821edb1 100644 --- a/packages/google-cloud-channel/google/cloud/channel_v1/gapic_version.py +++ b/packages/google-cloud-channel/google/cloud/channel_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.20.0" # {x-release-please-version} +__version__ = "1.20.1" # {x-release-please-version} diff --git a/packages/google-cloud-channel/google/cloud/channel_v1/services/cloud_channel_reports_service/client.py b/packages/google-cloud-channel/google/cloud/channel_v1/services/cloud_channel_reports_service/client.py index 7b838548916c..433e0999274b 100644 --- a/packages/google-cloud-channel/google/cloud/channel_v1/services/cloud_channel_reports_service/client.py +++ b/packages/google-cloud-channel/google/cloud/channel_v1/services/cloud_channel_reports_service/client.py @@ -488,36 +488,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudChannelReportsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -527,13 +497,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudChannelReportsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-channel/google/cloud/channel_v1/services/cloud_channel_service/client.py b/packages/google-cloud-channel/google/cloud/channel_v1/services/cloud_channel_service/client.py index 50bf88c61dba..65efe3abed74 100644 --- a/packages/google-cloud-channel/google/cloud/channel_v1/services/cloud_channel_service/client.py +++ b/packages/google-cloud-channel/google/cloud/channel_v1/services/cloud_channel_service/client.py @@ -669,36 +669,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudChannelServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -708,13 +678,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudChannelServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-channel/samples/generated_samples/snippet_metadata_google.cloud.channel.v1.json b/packages/google-cloud-channel/samples/generated_samples/snippet_metadata_google.cloud.channel.v1.json index 596e081cf9c6..246e3a4a4d85 100644 --- a/packages/google-cloud-channel/samples/generated_samples/snippet_metadata_google.cloud.channel.v1.json +++ b/packages/google-cloud-channel/samples/generated_samples/snippet_metadata_google.cloud.channel.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-channel", - "version": "1.20.0" + "version": "1.20.1" }, "snippets": [ { diff --git a/packages/google-cloud-channel/tests/unit/gapic/channel_v1/test_cloud_channel_reports_service.py b/packages/google-cloud-channel/tests/unit/gapic/channel_v1/test_cloud_channel_reports_service.py index 666777b16107..e9c6f7cf56a8 100644 --- a/packages/google-cloud-channel/tests/unit/gapic/channel_v1/test_cloud_channel_reports_service.py +++ b/packages/google-cloud-channel/tests/unit/gapic/channel_v1/test_cloud_channel_reports_service.py @@ -347,89 +347,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - CloudChannelReportsServiceClient, - transports.CloudChannelReportsServiceGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-channel/tests/unit/gapic/channel_v1/test_cloud_channel_service.py b/packages/google-cloud-channel/tests/unit/gapic/channel_v1/test_cloud_channel_service.py index 16d2ef018171..765870dc1078 100644 --- a/packages/google-cloud-channel/tests/unit/gapic/channel_v1/test_cloud_channel_service.py +++ b/packages/google-cloud-channel/tests/unit/gapic/channel_v1/test_cloud_channel_service.py @@ -356,89 +356,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - CloudChannelServiceClient, - transports.CloudChannelServiceGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md b/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md index 6bfc0f7a5bb6..44bbd336a68d 100644 --- a/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md +++ b/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.2.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-cloudcontrolspartner-v0.2.1...google-cloud-cloudcontrolspartner-v0.2.2) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.2.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-cloudcontrolspartner-v0.2.0...google-cloud-cloudcontrolspartner-v0.2.1) (2024-10-24) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/gapic_version.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/gapic_version.py index 6d8247638d59..d1a1a883babd 100644 --- a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/gapic_version.py +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.1" # {x-release-please-version} +__version__ = "0.2.2" # {x-release-please-version} diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/gapic_version.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/gapic_version.py index 6d8247638d59..d1a1a883babd 100644 --- a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/gapic_version.py +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.1" # {x-release-please-version} +__version__ = "0.2.2" # {x-release-please-version} diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/client.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/client.py index 82b86d2f3332..a3781f75beae 100644 --- a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/client.py +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/client.py @@ -592,36 +592,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -631,13 +601,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudControlsPartnerCoreClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/client.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/client.py index 0f7d9f952054..1cd8567abb42 100644 --- a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/client.py +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/client.py @@ -478,36 +478,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -517,13 +487,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudControlsPartnerMonitoringClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/gapic_version.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/gapic_version.py index 6d8247638d59..d1a1a883babd 100644 --- a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/gapic_version.py +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.1" # {x-release-please-version} +__version__ = "0.2.2" # {x-release-please-version} diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/client.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/client.py index 1896fa7459b7..48c0714b9751 100644 --- a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/client.py +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/client.py @@ -592,36 +592,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -631,13 +601,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudControlsPartnerCoreClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/client.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/client.py index edde6d0911ee..9c5de81b1d9e 100644 --- a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/client.py +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/client.py @@ -478,36 +478,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -517,13 +487,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudControlsPartnerMonitoringClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1.json b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1.json index 220f0f650c42..392fc5204423 100644 --- a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1.json +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-cloudcontrolspartner", - "version": "0.2.1" + "version": "0.2.2" }, "snippets": [ { diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1beta.json b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1beta.json index 33dd6a359fe1..d9b197cc0830 100644 --- a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1beta.json +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-cloudcontrolspartner", - "version": "0.2.1" + "version": "0.2.2" }, "snippets": [ { diff --git a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_core.py b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_core.py index 400ce936680a..f9919a53eb72 100644 --- a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_core.py +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_core.py @@ -343,94 +343,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - CloudControlsPartnerCoreClient, - transports.CloudControlsPartnerCoreGrpcTransport, - "grpc", - ), - ( - CloudControlsPartnerCoreClient, - transports.CloudControlsPartnerCoreRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_monitoring.py b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_monitoring.py index 378cd65cbe72..843ca40fda26 100644 --- a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_monitoring.py +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_monitoring.py @@ -352,94 +352,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - CloudControlsPartnerMonitoringClient, - transports.CloudControlsPartnerMonitoringGrpcTransport, - "grpc", - ), - ( - CloudControlsPartnerMonitoringClient, - transports.CloudControlsPartnerMonitoringRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_core.py b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_core.py index 34cc60cc0b8f..554f9c30d42d 100644 --- a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_core.py +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_core.py @@ -343,94 +343,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - CloudControlsPartnerCoreClient, - transports.CloudControlsPartnerCoreGrpcTransport, - "grpc", - ), - ( - CloudControlsPartnerCoreClient, - transports.CloudControlsPartnerCoreRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_monitoring.py b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_monitoring.py index 2c6f413e9378..5eb418b32ef6 100644 --- a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_monitoring.py +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_monitoring.py @@ -352,94 +352,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - CloudControlsPartnerMonitoringClient, - transports.CloudControlsPartnerMonitoringGrpcTransport, - "grpc", - ), - ( - CloudControlsPartnerMonitoringClient, - transports.CloudControlsPartnerMonitoringRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md b/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md index a3a9ec2ec011..877079e395ba 100644 --- a/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md +++ b/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-commerce-consumer-procurement-v0.1.9...google-cloud-commerce-consumer-procurement-v0.1.10) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.1.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-commerce-consumer-procurement-v0.1.8...google-cloud-commerce-consumer-procurement-v0.1.9) (2024-10-24) diff --git a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement/gapic_version.py b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement/gapic_version.py index f8ea948a9c30..9413c3341313 100644 --- a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement/gapic_version.py +++ b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.9" # {x-release-please-version} +__version__ = "0.1.10" # {x-release-please-version} diff --git a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/gapic_version.py b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/gapic_version.py index f8ea948a9c30..9413c3341313 100644 --- a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/gapic_version.py +++ b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.9" # {x-release-please-version} +__version__ = "0.1.10" # {x-release-please-version} diff --git a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/services/consumer_procurement_service/client.py b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/services/consumer_procurement_service/client.py index 119c0adfc5cc..cf83af1f0889 100644 --- a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/services/consumer_procurement_service/client.py +++ b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/services/consumer_procurement_service/client.py @@ -497,36 +497,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConsumerProcurementServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -536,13 +506,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ConsumerProcurementServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/services/license_management_service/client.py b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/services/license_management_service/client.py index 9aa5a85da06f..a943fc3ff392 100644 --- a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/services/license_management_service/client.py +++ b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1/services/license_management_service/client.py @@ -470,36 +470,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LicenseManagementServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -509,13 +479,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or LicenseManagementServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1alpha1/gapic_version.py b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1alpha1/gapic_version.py index f8ea948a9c30..9413c3341313 100644 --- a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1alpha1/gapic_version.py +++ b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.9" # {x-release-please-version} +__version__ = "0.1.10" # {x-release-please-version} diff --git a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1alpha1/services/consumer_procurement_service/client.py b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1alpha1/services/consumer_procurement_service/client.py index df680ceecc3a..0d17b8a8a05a 100644 --- a/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1alpha1/services/consumer_procurement_service/client.py +++ b/packages/google-cloud-commerce-consumer-procurement/google/cloud/commerce_consumer_procurement_v1alpha1/services/consumer_procurement_service/client.py @@ -497,36 +497,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConsumerProcurementServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -536,13 +506,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ConsumerProcurementServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-commerce-consumer-procurement/samples/generated_samples/snippet_metadata_google.cloud.commerce.consumer.procurement.v1.json b/packages/google-cloud-commerce-consumer-procurement/samples/generated_samples/snippet_metadata_google.cloud.commerce.consumer.procurement.v1.json index 78c1a769e8f3..bf50eef1c644 100644 --- a/packages/google-cloud-commerce-consumer-procurement/samples/generated_samples/snippet_metadata_google.cloud.commerce.consumer.procurement.v1.json +++ b/packages/google-cloud-commerce-consumer-procurement/samples/generated_samples/snippet_metadata_google.cloud.commerce.consumer.procurement.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-commerce-consumer-procurement", - "version": "0.1.9" + "version": "0.1.10" }, "snippets": [ { diff --git a/packages/google-cloud-commerce-consumer-procurement/samples/generated_samples/snippet_metadata_google.cloud.commerce.consumer.procurement.v1alpha1.json b/packages/google-cloud-commerce-consumer-procurement/samples/generated_samples/snippet_metadata_google.cloud.commerce.consumer.procurement.v1alpha1.json index 1fcc5668de22..0bc5add2d4eb 100644 --- a/packages/google-cloud-commerce-consumer-procurement/samples/generated_samples/snippet_metadata_google.cloud.commerce.consumer.procurement.v1alpha1.json +++ b/packages/google-cloud-commerce-consumer-procurement/samples/generated_samples/snippet_metadata_google.cloud.commerce.consumer.procurement.v1alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-commerce-consumer-procurement", - "version": "0.1.9" + "version": "0.1.10" }, "snippets": [ { diff --git a/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1/test_consumer_procurement_service.py b/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1/test_consumer_procurement_service.py index 59b5252ad41d..ccb358a69e42 100644 --- a/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1/test_consumer_procurement_service.py +++ b/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1/test_consumer_procurement_service.py @@ -353,94 +353,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ConsumerProcurementServiceClient, - transports.ConsumerProcurementServiceGrpcTransport, - "grpc", - ), - ( - ConsumerProcurementServiceClient, - transports.ConsumerProcurementServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1/test_license_management_service.py b/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1/test_license_management_service.py index ace34dbae51f..c6d289359a67 100644 --- a/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1/test_license_management_service.py +++ b/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1/test_license_management_service.py @@ -340,94 +340,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - LicenseManagementServiceClient, - transports.LicenseManagementServiceGrpcTransport, - "grpc", - ), - ( - LicenseManagementServiceClient, - transports.LicenseManagementServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1alpha1/test_consumer_procurement_service.py b/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1alpha1/test_consumer_procurement_service.py index dc9d5e178cbc..9b14a7739474 100644 --- a/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1alpha1/test_consumer_procurement_service.py +++ b/packages/google-cloud-commerce-consumer-procurement/tests/unit/gapic/commerce_consumer_procurement_v1alpha1/test_consumer_procurement_service.py @@ -353,94 +353,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ConsumerProcurementServiceClient, - transports.ConsumerProcurementServiceGrpcTransport, - "grpc", - ), - ( - ConsumerProcurementServiceClient, - transports.ConsumerProcurementServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/CHANGELOG.md b/packages/google-cloud-compute/CHANGELOG.md index be45071a6608..76900095afab 100644 --- a/packages/google-cloud-compute/CHANGELOG.md +++ b/packages/google-cloud-compute/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.20.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-compute-v1.20.0...google-cloud-compute-v1.20.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [1.20.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-compute-v1.19.2...google-cloud-compute-v1.20.0) (2024-10-24) diff --git a/packages/google-cloud-compute/google/cloud/compute/gapic_version.py b/packages/google-cloud-compute/google/cloud/compute/gapic_version.py index c8ba2b4c6a4f..4da8c821edb1 100644 --- a/packages/google-cloud-compute/google/cloud/compute/gapic_version.py +++ b/packages/google-cloud-compute/google/cloud/compute/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.20.0" # {x-release-please-version} +__version__ = "1.20.1" # {x-release-please-version} diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_version.py b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_version.py index c8ba2b4c6a4f..4da8c821edb1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_version.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.20.0" # {x-release-please-version} +__version__ = "1.20.1" # {x-release-please-version} diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/client.py index e3c490fde1e6..edb5e25be0a4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/accelerator_types/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AcceleratorTypesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AcceleratorTypesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/client.py index bd522fdd409c..ecdf130ba5ba 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/addresses/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AddressesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AddressesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/client.py index 654de7d186ed..d0584d2f6f64 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AutoscalersClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AutoscalersClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py index 8a244f67edab..af49015555ad 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BackendBucketsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BackendBucketsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): 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 8f6aa412de12..5227701eab54 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 @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BackendServicesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BackendServicesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/client.py index 3d2aa700494a..2982081397d9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/client.py @@ -433,36 +433,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DiskTypesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -472,13 +442,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DiskTypesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/client.py index d8f3e5164750..e0637dd7e56e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DisksClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DisksClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/client.py index 173f2d4d5e5c..690c9b15c0ec 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/external_vpn_gateways/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ExternalVpnGatewaysClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ExternalVpnGatewaysClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py index f5c93138a301..2d349546a644 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = FirewallPoliciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or FirewallPoliciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/client.py index a25be623c57b..6f02daa4fc23 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewalls/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = FirewallsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or FirewallsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/client.py index 479f226c6089..53e9a20ae3e0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/forwarding_rules/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ForwardingRulesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ForwardingRulesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py index aa361a0639af..116ff97f44f1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = GlobalAddressesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or GlobalAddressesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/client.py index 73fac29acac7..f90f59354a39 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_forwarding_rules/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = GlobalForwardingRulesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or GlobalForwardingRulesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py index 9c3968a6f6d0..dbb29bfda564 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = GlobalNetworkEndpointGroupsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or GlobalNetworkEndpointGroupsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/client.py index 582f90608011..3e95020aa9c5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_operations/client.py @@ -435,36 +435,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = GlobalOperationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -474,13 +444,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or GlobalOperationsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/client.py index 917163e5dde7..940d13a13863 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_organization_operations/client.py @@ -439,36 +439,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = GlobalOrganizationOperationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -478,13 +448,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or GlobalOrganizationOperationsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py index 31baf252244e..f085b6f6112f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_public_delegated_prefixes/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = GlobalPublicDelegatedPrefixesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or GlobalPublicDelegatedPrefixesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/client.py index 390ca315950a..35a872335d1f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = HealthChecksClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or HealthChecksClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/image_family_views/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/image_family_views/client.py index a92d0d7c5fe2..86b18ac725db 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/image_family_views/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/image_family_views/client.py @@ -434,36 +434,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ImageFamilyViewsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -473,13 +443,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ImageFamilyViewsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py index 28351f58c4eb..aae696350b3b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ImagesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ImagesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_manager_resize_requests/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_manager_resize_requests/client.py index 721dce6bb8a2..24ab6efa975d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_manager_resize_requests/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_manager_resize_requests/client.py @@ -449,36 +449,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InstanceGroupManagerResizeRequestsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -488,13 +458,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InstanceGroupManagerResizeRequestsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/client.py index d65cb6c12b37..59c234a1629e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InstanceGroupManagersClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InstanceGroupManagersClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/client.py index 9d4f7dea8bd7..603848969af8 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_groups/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InstanceGroupsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InstanceGroupsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_settings_service/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_settings_service/client.py index 6b2aa28abee9..16e2a1cf0315 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_settings_service/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_settings_service/client.py @@ -439,36 +439,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InstanceSettingsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -478,13 +448,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InstanceSettingsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/client.py index aab4c02a23b2..e7a398af57cf 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InstanceTemplatesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InstanceTemplatesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py index 489e7e33bbec..19127f30fa54 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InstancesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InstancesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/client.py index 64699398706e..f1b39d2a1396 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InstantSnapshotsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InstantSnapshotsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/client.py index 253f65fefb4b..5c532b970d23 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_attachments/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InterconnectAttachmentsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InterconnectAttachmentsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/client.py index 4c1955436e94..772bcb8aa217 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_locations/client.py @@ -437,36 +437,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InterconnectLocationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -476,13 +446,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InterconnectLocationsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_remote_locations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_remote_locations/client.py index de0a24175bb3..a156fef3d9b9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_remote_locations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnect_remote_locations/client.py @@ -439,36 +439,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InterconnectRemoteLocationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -478,13 +448,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InterconnectRemoteLocationsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/client.py index aaceb51c97e0..27a2081e65c3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/interconnects/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = InterconnectsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or InterconnectsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py index 19791d56e0c1..d2ef87ed2844 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/license_codes/client.py @@ -432,36 +432,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LicenseCodesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -471,13 +441,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or LicenseCodesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/client.py index 1e391cd879eb..1e462d31cc90 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/licenses/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LicensesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or LicensesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_images/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_images/client.py index d8263f56e910..a0fa79be98ae 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_images/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_images/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = MachineImagesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or MachineImagesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/client.py index 76b729111007..4d9e53608a0d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/client.py @@ -433,36 +433,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = MachineTypesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -472,13 +442,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or MachineTypesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_attachments/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_attachments/client.py index 2e218d73ffe9..76ae30b54d43 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_attachments/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_attachments/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NetworkAttachmentsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NetworkAttachmentsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_edge_security_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_edge_security_services/client.py index 491d38581d21..f936ca6897e7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_edge_security_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_edge_security_services/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NetworkEdgeSecurityServicesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NetworkEdgeSecurityServicesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/client.py index 5dd8c4475ead..ce11b9915b2c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NetworkEndpointGroupsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NetworkEndpointGroupsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_firewall_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_firewall_policies/client.py index 2ce5915f843f..7a6099444cfa 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_firewall_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_firewall_policies/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NetworkFirewallPoliciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NetworkFirewallPoliciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py index 2d6c6fdcca83..bede16bfd82e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NetworksClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NetworksClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/client.py index abfa417c23ea..482ea133127e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_groups/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NodeGroupsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NodeGroupsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/client.py index a37de9001145..57c083a84003 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NodeTemplatesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NodeTemplatesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/client.py index 5d20d96caba5..e7314ae950fd 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/client.py @@ -433,36 +433,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NodeTypesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -472,13 +442,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NodeTypesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/client.py index 8f3aae82b89e..718b854586da 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/packet_mirrorings/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PacketMirroringsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PacketMirroringsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/client.py index 3cd34365bdb5..68f359e65666 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ProjectsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ProjectsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/client.py index f988a2b8c93b..d48e695443a8 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_advertised_prefixes/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PublicAdvertisedPrefixesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PublicAdvertisedPrefixesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/client.py index 82989f868234..74e71da43c37 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/public_delegated_prefixes/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PublicDelegatedPrefixesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PublicDelegatedPrefixesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/client.py index 1fc50b748039..0ce4a252df1c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_autoscalers/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionAutoscalersClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionAutoscalersClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py index 76de8cad59dc..cb3560f83ac3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionBackendServicesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionBackendServicesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/client.py index 1df1123fcdb5..fbe87ac20479 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionCommitmentsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionCommitmentsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py index e985fbb9e895..af05f4178fd6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py @@ -435,36 +435,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionDiskTypesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -474,13 +444,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionDiskTypesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py index 6f97ae0f0868..68a0779f4ab3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionDisksClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionDisksClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/client.py index a26bcfd452d9..fb3642bd35c0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_check_services/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionHealthCheckServicesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionHealthCheckServicesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py index 30fea9ff210a..6a4f3b38feae 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionHealthChecksClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionHealthChecksClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/client.py index ce6498488bf9..ca845e244c9e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_group_managers/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionInstanceGroupManagersClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionInstanceGroupManagersClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/client.py index aacea1576000..950e78ff3d06 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_groups/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionInstanceGroupsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionInstanceGroupsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/client.py index 911bd2c6ae22..0bf07cbc064a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionInstanceTemplatesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionInstanceTemplatesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/client.py index b9838ead41aa..4a6f14f42ab0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instances/client.py @@ -437,36 +437,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionInstancesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -476,13 +446,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionInstancesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/client.py index 5f2772163b6a..9e92d404c9b6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionInstantSnapshotsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionInstantSnapshotsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py index ae10133ac5df..1ad24a848865 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionNetworkEndpointGroupsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionNetworkEndpointGroupsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_firewall_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_firewall_policies/client.py index 9ef32491766d..84de4e030a39 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_firewall_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_firewall_policies/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionNetworkFirewallPoliciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionNetworkFirewallPoliciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/client.py index 8f9b353ce1dd..387c17e95b14 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_notification_endpoints/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionNotificationEndpointsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionNotificationEndpointsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/client.py index 9afa7640b4ae..01082bdb8a44 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_operations/client.py @@ -435,36 +435,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionOperationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -474,13 +444,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionOperationsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_security_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_security_policies/client.py index 64cd68517767..a8e94a8e5768 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_security_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_security_policies/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionSecurityPoliciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionSecurityPoliciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/client.py index 601228014ab6..d22361bc8215 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_certificates/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionSslCertificatesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionSslCertificatesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_policies/client.py index 3dad39ce1e01..b5130166d07b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_ssl_policies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionSslPoliciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionSslPoliciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py index 4fa02950c9ee..758f93df3c10 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionTargetHttpProxiesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionTargetHttpProxiesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py index a0a67bf5464d..a4963f9723b4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionTargetHttpsProxiesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionTargetHttpsProxiesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_tcp_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_tcp_proxies/client.py index 401ea84bb7f3..62f5bbb2439c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_tcp_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_tcp_proxies/client.py @@ -440,36 +440,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionTargetTcpProxiesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -479,13 +449,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionTargetTcpProxiesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py index af510a30bb48..01c9416680f9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionUrlMapsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionUrlMapsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_zones/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_zones/client.py index d011854631b2..b7b7de589541 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_zones/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_zones/client.py @@ -433,36 +433,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionZonesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -472,13 +442,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionZonesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py index 9502b764063d..c2480d817bff 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py @@ -433,36 +433,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RegionsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -472,13 +442,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RegionsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/client.py index 712408dd11c0..a9353f050c70 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/reservations/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ReservationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ReservationsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/client.py index 15544bdf9cbd..29a86eb90826 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/resource_policies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ResourcePoliciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ResourcePoliciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py index 16244812f736..434841575504 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RoutersClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RoutersClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py index 4a180fbf1b7f..5602426546eb 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RoutesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RoutesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/client.py index 9866a67f1ee7..1a489a6fa42f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/security_policies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SecurityPoliciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SecurityPoliciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/service_attachments/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/service_attachments/client.py index ed32f20eb629..473c5260eca9 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/service_attachments/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/service_attachments/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ServiceAttachmentsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ServiceAttachmentsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshot_settings_service/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshot_settings_service/client.py index 96038398783e..db5865f609cc 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshot_settings_service/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshot_settings_service/client.py @@ -439,36 +439,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SnapshotSettingsServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -478,13 +448,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SnapshotSettingsServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): 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 48ac2b521d06..ab2732030918 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 @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SnapshotsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SnapshotsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/client.py index 9f8d79a499c5..cce8256d7fc3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SslCertificatesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SslCertificatesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/client.py index 5a0b7f483a54..1518200ad0b7 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SslPoliciesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SslPoliciesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/storage_pool_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/storage_pool_types/client.py index 66c919a57704..747e58f88d07 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/storage_pool_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/storage_pool_types/client.py @@ -435,36 +435,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = StoragePoolTypesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -474,13 +444,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or StoragePoolTypesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/storage_pools/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/storage_pools/client.py index e70dc879e944..9becfa36e20d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/storage_pools/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/storage_pools/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = StoragePoolsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or StoragePoolsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/client.py index 2ffc259804cf..be2fd4ed7237 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SubnetworksClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SubnetworksClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/client.py index 021e2c228f58..93bbd3659722 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_grpc_proxies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TargetGrpcProxiesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TargetGrpcProxiesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/client.py index 524ef81a25da..fa82cb8844cf 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TargetHttpProxiesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TargetHttpProxiesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/client.py index 5fc74cea1db9..aa470a359be4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TargetHttpsProxiesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TargetHttpsProxiesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/client.py index 2575ea47aa79..35b3296d45d6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TargetInstancesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TargetInstancesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/client.py index b575ba53b5cf..3be7e5490ca8 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TargetPoolsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TargetPoolsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py index ea783bb9a2fa..45690907b3b1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TargetSslProxiesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TargetSslProxiesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/client.py index ed1563d2f327..a7af51bee5ff 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TargetTcpProxiesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TargetTcpProxiesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/client.py index a9c6cb8df839..2f1ac9316952 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/client.py @@ -438,36 +438,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = TargetVpnGatewaysClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -477,13 +447,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or TargetVpnGatewaysClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/client.py index 9692ef9e40dd..b63934a5ea39 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = UrlMapsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or UrlMapsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/client.py index a3db517a80c0..cfcae3e45681 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = VpnGatewaysClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or VpnGatewaysClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/client.py index 86a982810b11..232f0698d33a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/client.py @@ -436,36 +436,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = VpnTunnelsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -475,13 +445,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or VpnTunnelsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/client.py index 8d59625da496..52f8986adcaa 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zone_operations/client.py @@ -435,36 +435,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ZoneOperationsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -474,13 +444,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ZoneOperationsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py index 6d712df2de77..b32dd13f3947 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py @@ -433,36 +433,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ZonesClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -472,13 +442,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ZonesClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): 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 0ad8cd732000..ea9465daf8b7 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 @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-compute", - "version": "1.20.0" + "version": "1.20.1" }, "snippets": [ { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_accelerator_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_accelerator_types.py index ea3620781e44..a554a17f9c63 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_accelerator_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_accelerator_types.py @@ -313,85 +313,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AcceleratorTypesClient, transports.AcceleratorTypesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_addresses.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_addresses.py index f5239fa822c0..52c35826df5c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_addresses.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_addresses.py @@ -294,85 +294,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AddressesClient, transports.AddressesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py index 334fa041814d..10367f5db405 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_autoscalers.py @@ -300,85 +300,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AutoscalersClient, transports.AutoscalersRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_buckets.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_buckets.py index 399fd0ce1c51..6a92db8a1b48 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_buckets.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_buckets.py @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BackendBucketsClient, transports.BackendBucketsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ 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 871813c27d2e..9027d4c3f03a 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 @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BackendServicesClient, transports.BackendServicesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disk_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disk_types.py index 1a3969d40975..81d46d2759cb 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disk_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disk_types.py @@ -287,85 +287,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DiskTypesClient, transports.DiskTypesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ 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 20b3cf9644a7..6b00abe854b8 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 @@ -275,85 +275,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DisksClient, transports.DisksRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_external_vpn_gateways.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_external_vpn_gateways.py index aa3fc2c28cae..71d639a5ff35 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_external_vpn_gateways.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_external_vpn_gateways.py @@ -334,89 +334,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ExternalVpnGatewaysClient, - transports.ExternalVpnGatewaysRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py index c44613ae2896..c7908589c660 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py @@ -320,85 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (FirewallPoliciesClient, transports.FirewallPoliciesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewalls.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewalls.py index 83b4a878122e..e60e8f020c86 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewalls.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewalls.py @@ -294,85 +294,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (FirewallsClient, transports.FirewallsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py index 008d2ef983b9..ae8980ee4be6 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ForwardingRulesClient, transports.ForwardingRulesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_addresses.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_addresses.py index 774d4d4b0b20..a5e189fb604f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_addresses.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_addresses.py @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (GlobalAddressesClient, transports.GlobalAddressesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py index ab27a72b4460..8025917c13e2 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - GlobalForwardingRulesClient, - transports.GlobalForwardingRulesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py index 51cde4807c37..1530d265791d 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_network_endpoint_groups.py @@ -344,89 +344,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - GlobalNetworkEndpointGroupsClient, - transports.GlobalNetworkEndpointGroupsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_operations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_operations.py index 6cbff281c1a9..6ac627a5ca57 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_operations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_operations.py @@ -313,85 +313,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (GlobalOperationsClient, transports.GlobalOperationsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_organization_operations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_organization_operations.py index 675eb3067bb3..9b9ac6b6c5cc 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_organization_operations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_organization_operations.py @@ -339,89 +339,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - GlobalOrganizationOperationsClient, - transports.GlobalOrganizationOperationsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py index 71523c1c2026..409352834f3f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py @@ -348,89 +348,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - GlobalPublicDelegatedPrefixesClient, - transports.GlobalPublicDelegatedPrefixesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_health_checks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_health_checks.py index e0ccf14dd212..e6847ad466c4 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_health_checks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_health_checks.py @@ -304,85 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (HealthChecksClient, transports.HealthChecksRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_image_family_views.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_image_family_views.py index 83669713c4a6..7bae0a5195af 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_image_family_views.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_image_family_views.py @@ -312,85 +312,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImageFamilyViewsClient, transports.ImageFamilyViewsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ 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 e4a9f1468951..b94b880fe868 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 @@ -279,85 +279,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ImagesClient, transports.ImagesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_manager_resize_requests.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_manager_resize_requests.py index 278cdfa2337c..98ed345ea93d 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_manager_resize_requests.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_manager_resize_requests.py @@ -354,89 +354,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - InstanceGroupManagerResizeRequestsClient, - transports.InstanceGroupManagerResizeRequestsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py index 5f055d896709..844889c26e9f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - InstanceGroupManagersClient, - transports.InstanceGroupManagersRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_groups.py index 5eaad7a68782..95e87f3db9cd 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_groups.py @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (InstanceGroupsClient, transports.InstanceGroupsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_settings_service.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_settings_service.py index 056921fff75b..9801d874beae 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_settings_service.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_settings_service.py @@ -335,89 +335,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - InstanceSettingsServiceClient, - transports.InstanceSettingsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py index a6caf3a470b2..07a5e906b43b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py @@ -328,85 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (InstanceTemplatesClient, transports.InstanceTemplatesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py index 7ec0982e002b..bb207772a7e2 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py @@ -294,85 +294,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (InstancesClient, transports.InstancesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instant_snapshots.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instant_snapshots.py index c796e79a7827..e6359ded7c50 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instant_snapshots.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instant_snapshots.py @@ -320,85 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (InstantSnapshotsClient, transports.InstantSnapshotsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_attachments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_attachments.py index 6fc7855b0497..0fea67a09c43 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_attachments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_attachments.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - InterconnectAttachmentsClient, - transports.InterconnectAttachmentsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_locations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_locations.py index dbaac9fb441b..e3d47b09cf5c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_locations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_locations.py @@ -329,89 +329,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - InterconnectLocationsClient, - transports.InterconnectLocationsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_remote_locations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_remote_locations.py index f0dd7a730818..cd8e2d9c5c72 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_remote_locations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnect_remote_locations.py @@ -337,89 +337,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - InterconnectRemoteLocationsClient, - transports.InterconnectRemoteLocationsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ 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 319d55f7cd55..51359bb6cb71 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 @@ -315,85 +315,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (InterconnectsClient, transports.InterconnectsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py index ec2ab714269c..334143e0fd3a 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_license_codes.py @@ -296,85 +296,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (LicenseCodesClient, transports.LicenseCodesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_licenses.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_licenses.py index 18e5e00c0d5c..1cd1af6d05f2 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_licenses.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_licenses.py @@ -287,85 +287,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (LicensesClient, transports.LicensesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py index 9849725306b5..d83263ebba29 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py @@ -315,85 +315,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (MachineImagesClient, transports.MachineImagesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_types.py index fecdc7603ed6..2561913c7fe1 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_types.py @@ -297,85 +297,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (MachineTypesClient, transports.MachineTypesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_attachments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_attachments.py index 6afd87292c28..2a4daab2af5c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_attachments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_attachments.py @@ -332,85 +332,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (NetworkAttachmentsClient, transports.NetworkAttachmentsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_edge_security_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_edge_security_services.py index ee101af2c254..2a65e7f6c25e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_edge_security_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_edge_security_services.py @@ -344,89 +344,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - NetworkEdgeSecurityServicesClient, - transports.NetworkEdgeSecurityServicesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py index c01ab77835aa..2869941601dd 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_endpoint_groups.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - NetworkEndpointGroupsClient, - transports.NetworkEndpointGroupsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_firewall_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_firewall_policies.py index 9c8600e18667..525c7080a964 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_firewall_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_firewall_policies.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - NetworkFirewallPoliciesClient, - transports.NetworkFirewallPoliciesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py index 6d50602fcba3..7f06d791adba 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_networks.py @@ -287,85 +287,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (NetworksClient, transports.NetworksRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_groups.py index 415c7dfa423f..2bae673bd29f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_groups.py @@ -296,85 +296,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (NodeGroupsClient, transports.NodeGroupsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_templates.py index ef29efc0f889..70811f71b58a 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_templates.py @@ -315,85 +315,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (NodeTemplatesClient, transports.NodeTemplatesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_types.py index 7698fd555902..af6654efc240 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_node_types.py @@ -287,85 +287,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (NodeTypesClient, transports.NodeTypesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_packet_mirrorings.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_packet_mirrorings.py index b6e6f7282870..606ff885e03b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_packet_mirrorings.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_packet_mirrorings.py @@ -320,85 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PacketMirroringsClient, transports.PacketMirroringsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_projects.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_projects.py index 5a29cd0b7afe..e0ddb2c1f1e1 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_projects.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_projects.py @@ -287,85 +287,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ProjectsClient, transports.ProjectsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py index 08bba598275f..d801f651e993 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_advertised_prefixes.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - PublicAdvertisedPrefixesClient, - transports.PublicAdvertisedPrefixesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py index 6c8d32af5a8f..db4a041cba8f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_public_delegated_prefixes.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - PublicDelegatedPrefixesClient, - transports.PublicDelegatedPrefixesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py index 010624999427..22d3737e2648 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_autoscalers.py @@ -328,85 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionAutoscalersClient, transports.RegionAutoscalersRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py index 1effe7b9b165..5d59f83ccd6b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionBackendServicesClient, - transports.RegionBackendServicesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py index cbafdda9fd84..d39e377af1a8 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py @@ -328,85 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionCommitmentsClient, transports.RegionCommitmentsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disk_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disk_types.py index 8a3adeed21ba..995fcdedbf99 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disk_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disk_types.py @@ -312,85 +312,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionDiskTypesClient, transports.RegionDiskTypesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ 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 559d5f9453f6..7c93efd3c4de 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 @@ -300,85 +300,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionDisksClient, transports.RegionDisksRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_check_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_check_services.py index 5cb9ecf4e1b9..ddb0b71a61fb 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_check_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_check_services.py @@ -340,89 +340,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionHealthCheckServicesClient, - transports.RegionHealthCheckServicesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_checks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_checks.py index 39583e7d0a1f..ba999e7abeeb 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_checks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_health_checks.py @@ -332,85 +332,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionHealthChecksClient, transports.RegionHealthChecksRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py index 3db016494a39..493f109f562d 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py @@ -344,89 +344,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionInstanceGroupManagersClient, - transports.RegionInstanceGroupManagersRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_groups.py index 5a2563bd683b..61bd7eba7093 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_groups.py @@ -334,89 +334,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionInstanceGroupsClient, - transports.RegionInstanceGroupsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py index 9d8b6ec8fc63..72ec12d6e336 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionInstanceTemplatesClient, - transports.RegionInstanceTemplatesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py index 02963274d0e5..da93211f1175 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py @@ -318,85 +318,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionInstancesClient, transports.RegionInstancesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instant_snapshots.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instant_snapshots.py index 5d15f52a5e30..9b46a646b586 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instant_snapshots.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instant_snapshots.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionInstantSnapshotsClient, - transports.RegionInstantSnapshotsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py index 380cf85f2317..8001b97882c3 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_endpoint_groups.py @@ -344,89 +344,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionNetworkEndpointGroupsClient, - transports.RegionNetworkEndpointGroupsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_firewall_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_firewall_policies.py index 15094ba9f0cf..6ea11a0f9ec5 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_firewall_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_firewall_policies.py @@ -348,89 +348,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionNetworkFirewallPoliciesClient, - transports.RegionNetworkFirewallPoliciesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py index 371d5cff4ec6..66a03f6caa5a 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_notification_endpoints.py @@ -344,89 +344,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionNotificationEndpointsClient, - transports.RegionNotificationEndpointsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_operations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_operations.py index 9c44e5e1cd9d..887773b60a40 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_operations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_operations.py @@ -313,85 +313,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionOperationsClient, transports.RegionOperationsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ 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 b645155e5011..6a1893ee685c 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 @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionSecurityPoliciesClient, - transports.RegionSecurityPoliciesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py index 59c296f291c2..15c39dff4cae 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_certificates.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionSslCertificatesClient, - transports.RegionSslCertificatesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_policies.py index 0b363004a3dd..6c3b759a4e5c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_ssl_policies.py @@ -328,85 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionSslPoliciesClient, transports.RegionSslPoliciesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py index ba9ed04184db..2bafa4c8a6c9 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_http_proxies.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionTargetHttpProxiesClient, - transports.RegionTargetHttpProxiesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py index a77e9a80b727..4352750a80d3 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_https_proxies.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionTargetHttpsProxiesClient, - transports.RegionTargetHttpsProxiesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_tcp_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_tcp_proxies.py index 1084142cc685..9452891c094e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_tcp_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_tcp_proxies.py @@ -336,89 +336,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - RegionTargetTcpProxiesClient, - transports.RegionTargetTcpProxiesRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py index 3315e7d5a947..bd71d6d3df10 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py @@ -315,85 +315,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionUrlMapsClient, transports.RegionUrlMapsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_zones.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_zones.py index 1b57301a6ace..52330f10a499 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_zones.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_zones.py @@ -293,85 +293,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionZonesClient, transports.RegionZonesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_regions.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_regions.py index bdf72eb03adf..c90bf14c6e22 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_regions.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_regions.py @@ -273,85 +273,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RegionsClient, transports.RegionsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py index e917cda7411d..e0a9da7785e7 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py @@ -304,85 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ReservationsClient, transports.ReservationsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_resource_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_resource_policies.py index fae25a36f82c..501c5586a990 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_resource_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_resource_policies.py @@ -320,85 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ResourcePoliciesClient, transports.ResourcePoliciesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py index 94d4d91118a2..21c00c53ee6c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py @@ -280,85 +280,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RoutersClient, transports.RoutersRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routes.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routes.py index 2751e4e2423a..889a91f49b9c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routes.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routes.py @@ -279,85 +279,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RoutesClient, transports.RoutesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ 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 96c20c1b455d..0a0e8c63e74a 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 @@ -320,85 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_service_attachments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_service_attachments.py index 04bc32ebb9f2..2e57bf09e24f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_service_attachments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_service_attachments.py @@ -332,85 +332,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ServiceAttachmentsClient, transports.ServiceAttachmentsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshot_settings_service.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshot_settings_service.py index e880942cd5ff..faf681c86755 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshot_settings_service.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshot_settings_service.py @@ -335,89 +335,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - SnapshotSettingsServiceClient, - transports.SnapshotSettingsServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ 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 8955787274f3..c36064ae4c41 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 @@ -294,85 +294,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SnapshotsClient, transports.SnapshotsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_certificates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_certificates.py index d5872d0205f5..7e1b6b8982b8 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_certificates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_certificates.py @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SslCertificatesClient, transports.SslCertificatesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py index dbc44d828869..5d359a75d47c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_ssl_policies.py @@ -300,85 +300,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SslPoliciesClient, transports.SslPoliciesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_storage_pool_types.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_storage_pool_types.py index 64c2535f704d..93d856c66009 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_storage_pool_types.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_storage_pool_types.py @@ -313,85 +313,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (StoragePoolTypesClient, transports.StoragePoolTypesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_storage_pools.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_storage_pools.py index 7e60cfcfac79..53406346362b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_storage_pools.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_storage_pools.py @@ -304,85 +304,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (StoragePoolsClient, transports.StoragePoolsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py index 9c76455c444b..a25133568354 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py @@ -300,85 +300,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SubnetworksClient, transports.SubnetworksRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py index ad66e6310c6c..f06801e20255 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_grpc_proxies.py @@ -328,85 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TargetGrpcProxiesClient, transports.TargetGrpcProxiesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_http_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_http_proxies.py index 28dc281a14f0..ff2ad804d063 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_http_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_http_proxies.py @@ -328,85 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TargetHttpProxiesClient, transports.TargetHttpProxiesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_https_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_https_proxies.py index bfdffab74960..d27ff127ed1c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_https_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_https_proxies.py @@ -332,85 +332,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TargetHttpsProxiesClient, transports.TargetHttpsProxiesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_instances.py index 324b8018b35c..b39a05dd8014 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_instances.py @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TargetInstancesClient, transports.TargetInstancesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_pools.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_pools.py index 107f272c3e87..00e218974820 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_pools.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_pools.py @@ -300,85 +300,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TargetPoolsClient, transports.TargetPoolsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py index 8965059f00a7..d924309b2a3e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_ssl_proxies.py @@ -320,85 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TargetSslProxiesClient, transports.TargetSslProxiesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py index 5dc93493a26b..49c04c4d54ec 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py @@ -320,85 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TargetTcpProxiesClient, transports.TargetTcpProxiesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py index 8e46c247261d..82438edf225b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_vpn_gateways.py @@ -328,85 +328,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (TargetVpnGatewaysClient, transports.TargetVpnGatewaysRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py index 07196e0bded2..464a16258e47 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py @@ -280,85 +280,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (UrlMapsClient, transports.UrlMapsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_gateways.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_gateways.py index 398fb9fa1d55..0f396a713d71 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_gateways.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_gateways.py @@ -300,85 +300,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (VpnGatewaysClient, transports.VpnGatewaysRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_tunnels.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_tunnels.py index 6cacf168c1ca..a458b42d1c40 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_tunnels.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_vpn_tunnels.py @@ -296,85 +296,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (VpnTunnelsClient, transports.VpnTunnelsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zone_operations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zone_operations.py index aa550923abd7..9b80960f5c65 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zone_operations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zone_operations.py @@ -312,85 +312,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ZoneOperationsClient, transports.ZoneOperationsRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zones.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zones.py index b2e8b8288236..66afb9cfbc46 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zones.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_zones.py @@ -268,85 +268,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ZonesClient, transports.ZonesRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-confidentialcomputing/CHANGELOG.md b/packages/google-cloud-confidentialcomputing/CHANGELOG.md index 6a5f1a01138a..8735e8541f1a 100644 --- a/packages/google-cloud-confidentialcomputing/CHANGELOG.md +++ b/packages/google-cloud-confidentialcomputing/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-confidentialcomputing-v0.4.12...google-cloud-confidentialcomputing-v0.4.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.4.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-confidentialcomputing-v0.4.11...google-cloud-confidentialcomputing-v0.4.12) (2024-10-24) diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing/gapic_version.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing/gapic_version.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/gapic_version.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/gapic_version.py index db2ef16a95a4..9b19e5f10e00 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/gapic_version.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.4.12" # {x-release-please-version} +__version__ = "0.4.13" # {x-release-please-version} diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/client.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/client.py index 1ea039704a5f..e2541c1ea369 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/client.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/client.py @@ -466,36 +466,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConfidentialComputingClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -505,13 +475,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ConfidentialComputingClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-confidentialcomputing/samples/generated_samples/snippet_metadata_google.cloud.confidentialcomputing.v1.json b/packages/google-cloud-confidentialcomputing/samples/generated_samples/snippet_metadata_google.cloud.confidentialcomputing.v1.json index 01320d796a52..75ee32ba28cb 100644 --- a/packages/google-cloud-confidentialcomputing/samples/generated_samples/snippet_metadata_google.cloud.confidentialcomputing.v1.json +++ b/packages/google-cloud-confidentialcomputing/samples/generated_samples/snippet_metadata_google.cloud.confidentialcomputing.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-confidentialcomputing", - "version": "0.4.12" + "version": "0.4.13" }, "snippets": [ { diff --git a/packages/google-cloud-confidentialcomputing/tests/unit/gapic/confidentialcomputing_v1/test_confidential_computing.py b/packages/google-cloud-confidentialcomputing/tests/unit/gapic/confidentialcomputing_v1/test_confidential_computing.py index 95dc55470180..b3e488623d27 100644 --- a/packages/google-cloud-confidentialcomputing/tests/unit/gapic/confidentialcomputing_v1/test_confidential_computing.py +++ b/packages/google-cloud-confidentialcomputing/tests/unit/gapic/confidentialcomputing_v1/test_confidential_computing.py @@ -337,94 +337,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ConfidentialComputingClient, - transports.ConfidentialComputingGrpcTransport, - "grpc", - ), - ( - ConfidentialComputingClient, - transports.ConfidentialComputingRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-config/CHANGELOG.md b/packages/google-cloud-config/CHANGELOG.md index d25be5522426..02e15562c627 100644 --- a/packages/google-cloud-config/CHANGELOG.md +++ b/packages/google-cloud-config/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-config-v0.1.12...google-cloud-config-v0.1.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.1.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-config-v0.1.11...google-cloud-config-v0.1.12) (2024-10-24) diff --git a/packages/google-cloud-config/google/cloud/config/gapic_version.py b/packages/google-cloud-config/google/cloud/config/gapic_version.py index 17bbab4c1877..7daf9a1dd221 100644 --- a/packages/google-cloud-config/google/cloud/config/gapic_version.py +++ b/packages/google-cloud-config/google/cloud/config/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.12" # {x-release-please-version} +__version__ = "0.1.13" # {x-release-please-version} diff --git a/packages/google-cloud-config/google/cloud/config_v1/gapic_version.py b/packages/google-cloud-config/google/cloud/config_v1/gapic_version.py index 17bbab4c1877..7daf9a1dd221 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/gapic_version.py +++ b/packages/google-cloud-config/google/cloud/config_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.12" # {x-release-please-version} +__version__ = "0.1.13" # {x-release-please-version} diff --git a/packages/google-cloud-config/google/cloud/config_v1/services/config/client.py b/packages/google-cloud-config/google/cloud/config_v1/services/config/client.py index 2d5959bd7a30..87fb2897e6c5 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/services/config/client.py +++ b/packages/google-cloud-config/google/cloud/config_v1/services/config/client.py @@ -612,36 +612,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ConfigClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -651,13 +621,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ConfigClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-config/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json b/packages/google-cloud-config/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json index 5b593664167e..b930b4cd32a8 100644 --- a/packages/google-cloud-config/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json +++ b/packages/google-cloud-config/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-config", - "version": "0.1.12" + "version": "0.1.13" }, "snippets": [ { diff --git a/packages/google-cloud-config/tests/unit/gapic/config_v1/test_config.py b/packages/google-cloud-config/tests/unit/gapic/config_v1/test_config.py index 60fb76c763bc..aca6fcb728b7 100644 --- a/packages/google-cloud-config/tests/unit/gapic/config_v1/test_config.py +++ b/packages/google-cloud-config/tests/unit/gapic/config_v1/test_config.py @@ -301,86 +301,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ConfigClient, transports.ConfigGrpcTransport, "grpc"), - (ConfigClient, transports.ConfigRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-contact-center-insights/CHANGELOG.md b/packages/google-cloud-contact-center-insights/CHANGELOG.md index ddb7f228b6fa..a3d9bb516036 100644 --- a/packages/google-cloud-contact-center-insights/CHANGELOG.md +++ b/packages/google-cloud-contact-center-insights/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.19.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-contact-center-insights-v1.19.0...google-cloud-contact-center-insights-v1.19.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [1.19.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-contact-center-insights-v1.18.0...google-cloud-contact-center-insights-v1.19.0) (2024-10-24) diff --git a/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights/gapic_version.py b/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights/gapic_version.py index f1337c609ff8..68899264edad 100644 --- a/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights/gapic_version.py +++ b/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.19.0" # {x-release-please-version} +__version__ = "1.19.1" # {x-release-please-version} diff --git a/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights_v1/gapic_version.py b/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights_v1/gapic_version.py index f1337c609ff8..68899264edad 100644 --- a/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights_v1/gapic_version.py +++ b/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.19.0" # {x-release-please-version} +__version__ = "1.19.1" # {x-release-please-version} diff --git a/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights_v1/services/contact_center_insights/client.py b/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights_v1/services/contact_center_insights/client.py index b9ab0723ffe0..084d0e6239c6 100644 --- a/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights_v1/services/contact_center_insights/client.py +++ b/packages/google-cloud-contact-center-insights/google/cloud/contact_center_insights_v1/services/contact_center_insights/client.py @@ -701,36 +701,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ContactCenterInsightsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -740,13 +710,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ContactCenterInsightsClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-contact-center-insights/samples/generated_samples/snippet_metadata_google.cloud.contactcenterinsights.v1.json b/packages/google-cloud-contact-center-insights/samples/generated_samples/snippet_metadata_google.cloud.contactcenterinsights.v1.json index 603c1afb27d7..90d789df11c2 100644 --- a/packages/google-cloud-contact-center-insights/samples/generated_samples/snippet_metadata_google.cloud.contactcenterinsights.v1.json +++ b/packages/google-cloud-contact-center-insights/samples/generated_samples/snippet_metadata_google.cloud.contactcenterinsights.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-contact-center-insights", - "version": "1.19.0" + "version": "1.19.1" }, "snippets": [ { diff --git a/packages/google-cloud-contact-center-insights/tests/unit/gapic/contact_center_insights_v1/test_contact_center_insights.py b/packages/google-cloud-contact-center-insights/tests/unit/gapic/contact_center_insights_v1/test_contact_center_insights.py index 8356d8f5c948..bf8f9a66c041 100644 --- a/packages/google-cloud-contact-center-insights/tests/unit/gapic/contact_center_insights_v1/test_contact_center_insights.py +++ b/packages/google-cloud-contact-center-insights/tests/unit/gapic/contact_center_insights_v1/test_contact_center_insights.py @@ -352,94 +352,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - ContactCenterInsightsClient, - transports.ContactCenterInsightsGrpcTransport, - "grpc", - ), - ( - ContactCenterInsightsClient, - transports.ContactCenterInsightsRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-contentwarehouse/CHANGELOG.md b/packages/google-cloud-contentwarehouse/CHANGELOG.md index 4ffa38187552..e5498ffd9b9f 100644 --- a/packages/google-cloud-contentwarehouse/CHANGELOG.md +++ b/packages/google-cloud-contentwarehouse/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.7.11](https://github.com/googleapis/google-cloud-python/compare/google-cloud-contentwarehouse-v0.7.10...google-cloud-contentwarehouse-v0.7.11) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.7.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-contentwarehouse-v0.7.9...google-cloud-contentwarehouse-v0.7.10) (2024-10-24) diff --git a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse/gapic_version.py b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse/gapic_version.py index a2381e52ccc8..2abd5a01e3d6 100644 --- a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse/gapic_version.py +++ b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.7.10" # {x-release-please-version} +__version__ = "0.7.11" # {x-release-please-version} diff --git a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/gapic_version.py b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/gapic_version.py index a2381e52ccc8..2abd5a01e3d6 100644 --- a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/gapic_version.py +++ b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.7.10" # {x-release-please-version} +__version__ = "0.7.11" # {x-release-please-version} diff --git a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_link_service/client.py b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_link_service/client.py index f471d7e4055a..afbf8681d390 100644 --- a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_link_service/client.py +++ b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_link_service/client.py @@ -491,36 +491,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DocumentLinkServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -530,13 +500,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DocumentLinkServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_schema_service/client.py b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_schema_service/client.py index bf9bc88a165a..1eb0c4a265c9 100644 --- a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_schema_service/client.py +++ b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_schema_service/client.py @@ -487,36 +487,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DocumentSchemaServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -526,13 +496,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DocumentSchemaServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_service/client.py b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_service/client.py index 704d3e272d38..d72800798906 100644 --- a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_service/client.py +++ b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_service/client.py @@ -511,36 +511,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DocumentServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -550,13 +520,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DocumentServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/pipeline_service/client.py b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/pipeline_service/client.py index 613390fa4b26..b1df7f0b7659 100644 --- a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/pipeline_service/client.py +++ b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/pipeline_service/client.py @@ -481,36 +481,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PipelineServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -520,13 +490,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PipelineServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/rule_set_service/client.py b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/rule_set_service/client.py index 7588c418229a..34dfb64600e6 100644 --- a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/rule_set_service/client.py +++ b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/rule_set_service/client.py @@ -502,36 +502,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = RuleSetServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -541,13 +511,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or RuleSetServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/synonym_set_service/client.py b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/synonym_set_service/client.py index db6940d5f1a9..59ac12cd7dd4 100644 --- a/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/synonym_set_service/client.py +++ b/packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/synonym_set_service/client.py @@ -483,36 +483,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SynonymSetServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -522,13 +492,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SynonymSetServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-contentwarehouse/samples/generated_samples/snippet_metadata_google.cloud.contentwarehouse.v1.json b/packages/google-cloud-contentwarehouse/samples/generated_samples/snippet_metadata_google.cloud.contentwarehouse.v1.json index d05c1097114e..1edb6ed03680 100644 --- a/packages/google-cloud-contentwarehouse/samples/generated_samples/snippet_metadata_google.cloud.contentwarehouse.v1.json +++ b/packages/google-cloud-contentwarehouse/samples/generated_samples/snippet_metadata_google.cloud.contentwarehouse.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-contentwarehouse", - "version": "0.7.10" + "version": "0.7.11" }, "snippets": [ { diff --git a/packages/google-cloud-contentwarehouse/setup.py b/packages/google-cloud-contentwarehouse/setup.py index b33a14f0957b..a04ce63bb651 100644 --- a/packages/google-cloud-contentwarehouse/setup.py +++ b/packages/google-cloud-contentwarehouse/setup.py @@ -48,7 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-cloud-documentai >= 2.0.0, <3.0.0dev", + "google-cloud-documentai >= 2.0.0, <4.0.0dev", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] extras = {} diff --git a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_link_service.py b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_link_service.py index 8719c6a72dfa..a9065d3872b0 100644 --- a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_link_service.py +++ b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_link_service.py @@ -339,94 +339,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - DocumentLinkServiceClient, - transports.DocumentLinkServiceGrpcTransport, - "grpc", - ), - ( - DocumentLinkServiceClient, - transports.DocumentLinkServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_schema_service.py b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_schema_service.py index 08b77780da53..cbc4a7bc860c 100644 --- a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_schema_service.py +++ b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_schema_service.py @@ -341,94 +341,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - DocumentSchemaServiceClient, - transports.DocumentSchemaServiceGrpcTransport, - "grpc", - ), - ( - DocumentSchemaServiceClient, - transports.DocumentSchemaServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_service.py b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_service.py index 3979662a0f5d..fad5ef9c602e 100644 --- a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_service.py +++ b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_document_service.py @@ -344,86 +344,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_pipeline_service.py b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_pipeline_service.py index 94ad45d2a36c..68584d2b2dd6 100644 --- a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_pipeline_service.py +++ b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_pipeline_service.py @@ -329,86 +329,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PipelineServiceClient, transports.PipelineServiceGrpcTransport, "grpc"), - (PipelineServiceClient, transports.PipelineServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_rule_set_service.py b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_rule_set_service.py index 9c8e942614e0..cf7df9f6e207 100644 --- a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_rule_set_service.py +++ b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_rule_set_service.py @@ -321,86 +321,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (RuleSetServiceClient, transports.RuleSetServiceGrpcTransport, "grpc"), - (RuleSetServiceClient, transports.RuleSetServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_synonym_set_service.py b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_synonym_set_service.py index f2017d3f10c6..09d8d00a5e40 100644 --- a/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_synonym_set_service.py +++ b/packages/google-cloud-contentwarehouse/tests/unit/gapic/contentwarehouse_v1/test_synonym_set_service.py @@ -331,86 +331,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SynonymSetServiceClient, transports.SynonymSetServiceGrpcTransport, "grpc"), - (SynonymSetServiceClient, transports.SynonymSetServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-data-fusion/CHANGELOG.md b/packages/google-cloud-data-fusion/CHANGELOG.md index 6ca5b517e93a..da9e1261ed76 100644 --- a/packages/google-cloud-data-fusion/CHANGELOG.md +++ b/packages/google-cloud-data-fusion/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-data-fusion-v1.11.0...google-cloud-data-fusion-v1.11.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [1.11.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-data-fusion-v1.10.5...google-cloud-data-fusion-v1.11.0) (2024-10-24) diff --git a/packages/google-cloud-data-fusion/google/cloud/data_fusion/gapic_version.py b/packages/google-cloud-data-fusion/google/cloud/data_fusion/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-data-fusion/google/cloud/data_fusion/gapic_version.py +++ b/packages/google-cloud-data-fusion/google/cloud/data_fusion/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-data-fusion/google/cloud/data_fusion_v1/gapic_version.py b/packages/google-cloud-data-fusion/google/cloud/data_fusion_v1/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-data-fusion/google/cloud/data_fusion_v1/gapic_version.py +++ b/packages/google-cloud-data-fusion/google/cloud/data_fusion_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-data-fusion/google/cloud/data_fusion_v1/services/data_fusion/client.py b/packages/google-cloud-data-fusion/google/cloud/data_fusion_v1/services/data_fusion/client.py index 1fb70174685f..cf39d118fcfa 100644 --- a/packages/google-cloud-data-fusion/google/cloud/data_fusion_v1/services/data_fusion/client.py +++ b/packages/google-cloud-data-fusion/google/cloud/data_fusion_v1/services/data_fusion/client.py @@ -492,36 +492,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataFusionClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -531,13 +501,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataFusionClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-data-fusion/samples/generated_samples/snippet_metadata_google.cloud.datafusion.v1.json b/packages/google-cloud-data-fusion/samples/generated_samples/snippet_metadata_google.cloud.datafusion.v1.json index b32a43bdfc4a..b41568b9bbc7 100644 --- a/packages/google-cloud-data-fusion/samples/generated_samples/snippet_metadata_google.cloud.datafusion.v1.json +++ b/packages/google-cloud-data-fusion/samples/generated_samples/snippet_metadata_google.cloud.datafusion.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-data-fusion", - "version": "1.11.0" + "version": "1.11.1" }, "snippets": [ { diff --git a/packages/google-cloud-data-fusion/tests/unit/gapic/data_fusion_v1/test_data_fusion.py b/packages/google-cloud-data-fusion/tests/unit/gapic/data_fusion_v1/test_data_fusion.py index 2189f4bff846..e52ab4ef600f 100644 --- a/packages/google-cloud-data-fusion/tests/unit/gapic/data_fusion_v1/test_data_fusion.py +++ b/packages/google-cloud-data-fusion/tests/unit/gapic/data_fusion_v1/test_data_fusion.py @@ -308,86 +308,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DataFusionClient, transports.DataFusionGrpcTransport, "grpc"), - (DataFusionClient, transports.DataFusionRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-data-qna/CHANGELOG.md b/packages/google-cloud-data-qna/CHANGELOG.md index 56160c2d9e32..d92e099d6836 100644 --- a/packages/google-cloud-data-qna/CHANGELOG.md +++ b/packages/google-cloud-data-qna/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.10.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-data-qna-v0.10.12...google-cloud-data-qna-v0.10.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.10.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-data-qna-v0.10.11...google-cloud-data-qna-v0.10.12) (2024-10-24) diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna/gapic_version.py b/packages/google-cloud-data-qna/google/cloud/dataqna/gapic_version.py index dbb72468cf59..3de369591024 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna/gapic_version.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.12" # {x-release-please-version} +__version__ = "0.10.13" # {x-release-please-version} diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/gapic_version.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/gapic_version.py index dbb72468cf59..3de369591024 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/gapic_version.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.12" # {x-release-please-version} +__version__ = "0.10.13" # {x-release-please-version} diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py index 6de5b4c512ba..f0830404cdd8 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/auto_suggestion_service/client.py @@ -511,36 +511,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AutoSuggestionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -550,13 +520,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AutoSuggestionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/client.py b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/client.py index a1793ae50ed9..9133706d7721 100644 --- a/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/client.py +++ b/packages/google-cloud-data-qna/google/cloud/dataqna_v1alpha/services/question_service/client.py @@ -507,36 +507,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = QuestionServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -546,13 +516,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or QuestionServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-data-qna/samples/generated_samples/snippet_metadata_google.cloud.dataqna.v1alpha.json b/packages/google-cloud-data-qna/samples/generated_samples/snippet_metadata_google.cloud.dataqna.v1alpha.json index c7642dc3d0a2..ddd45f0cdee4 100644 --- a/packages/google-cloud-data-qna/samples/generated_samples/snippet_metadata_google.cloud.dataqna.v1alpha.json +++ b/packages/google-cloud-data-qna/samples/generated_samples/snippet_metadata_google.cloud.dataqna.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-data-qna", - "version": "0.10.12" + "version": "0.10.13" }, "snippets": [ { diff --git a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py index a14557af276e..8601ec13a534 100644 --- a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py +++ b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_auto_suggestion_service.py @@ -334,94 +334,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AutoSuggestionServiceClient, - transports.AutoSuggestionServiceGrpcTransport, - "grpc", - ), - ( - AutoSuggestionServiceClient, - transports.AutoSuggestionServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_question_service.py b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_question_service.py index 73c312970063..0bab8ee42283 100644 --- a/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_question_service.py +++ b/packages/google-cloud-data-qna/tests/unit/gapic/dataqna_v1alpha/test_question_service.py @@ -326,86 +326,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (QuestionServiceClient, transports.QuestionServiceGrpcTransport, "grpc"), - (QuestionServiceClient, transports.QuestionServiceRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datacatalog-lineage/CHANGELOG.md b/packages/google-cloud-datacatalog-lineage/CHANGELOG.md index ce5941de19ee..6e6240d17b4e 100644 --- a/packages/google-cloud-datacatalog-lineage/CHANGELOG.md +++ b/packages/google-cloud-datacatalog-lineage/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datacatalog-lineage-v0.3.9...google-cloud-datacatalog-lineage-v0.3.10) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.3.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datacatalog-lineage-v0.3.8...google-cloud-datacatalog-lineage-v0.3.9) (2024-10-24) diff --git a/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage/gapic_version.py b/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage/gapic_version.py index d24d3fba9057..3425e3287cda 100644 --- a/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage/gapic_version.py +++ b/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.9" # {x-release-please-version} +__version__ = "0.3.10" # {x-release-please-version} diff --git a/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage_v1/gapic_version.py b/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage_v1/gapic_version.py index d24d3fba9057..3425e3287cda 100644 --- a/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage_v1/gapic_version.py +++ b/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.9" # {x-release-please-version} +__version__ = "0.3.10" # {x-release-please-version} diff --git a/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage_v1/services/lineage/client.py b/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage_v1/services/lineage/client.py index 74b00d699b5b..703d05764ee2 100644 --- a/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage_v1/services/lineage/client.py +++ b/packages/google-cloud-datacatalog-lineage/google/cloud/datacatalog_lineage_v1/services/lineage/client.py @@ -522,36 +522,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = LineageClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -561,13 +531,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or LineageClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datacatalog-lineage/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.lineage.v1.json b/packages/google-cloud-datacatalog-lineage/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.lineage.v1.json index b3c5117586d8..3abf1395c457 100644 --- a/packages/google-cloud-datacatalog-lineage/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.lineage.v1.json +++ b/packages/google-cloud-datacatalog-lineage/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.lineage.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-datacatalog-lineage", - "version": "0.3.9" + "version": "0.3.10" }, "snippets": [ { diff --git a/packages/google-cloud-datacatalog-lineage/tests/unit/gapic/datacatalog_lineage_v1/test_lineage.py b/packages/google-cloud-datacatalog-lineage/tests/unit/gapic/datacatalog_lineage_v1/test_lineage.py index 6d5913e203ae..5efbc8276517 100644 --- a/packages/google-cloud-datacatalog-lineage/tests/unit/gapic/datacatalog_lineage_v1/test_lineage.py +++ b/packages/google-cloud-datacatalog-lineage/tests/unit/gapic/datacatalog_lineage_v1/test_lineage.py @@ -297,86 +297,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (LineageClient, transports.LineageGrpcTransport, "grpc"), - (LineageClient, transports.LineageRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datacatalog/CHANGELOG.md b/packages/google-cloud-datacatalog/CHANGELOG.md index e0f697d191f1..77d144fa2da2 100644 --- a/packages/google-cloud-datacatalog/CHANGELOG.md +++ b/packages/google-cloud-datacatalog/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-datacatalog/#history +## [3.21.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datacatalog-v3.21.0...google-cloud-datacatalog-v3.21.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [3.21.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datacatalog-v3.20.1...google-cloud-datacatalog-v3.21.0) (2024-10-24) diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog/gapic_version.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog/gapic_version.py index c843b7364c5d..cb24f2360f5a 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog/gapic_version.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.21.0" # {x-release-please-version} +__version__ = "3.21.1" # {x-release-please-version} diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/gapic_version.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/gapic_version.py index c843b7364c5d..cb24f2360f5a 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/gapic_version.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.21.0" # {x-release-please-version} +__version__ = "3.21.1" # {x-release-please-version} diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/client.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/client.py index 3e92d17deb06..ab94e4e24b8c 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/client.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/client.py @@ -601,36 +601,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataCatalogClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -640,13 +610,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataCatalogClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py index 80991e5efa03..e0b8a49d9e11 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/policy_tag_manager/client.py @@ -493,36 +493,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PolicyTagManagerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -532,13 +502,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PolicyTagManagerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py index fc21f2be6f2c..6c90b1f76b28 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/policy_tag_manager_serialization/client.py @@ -477,36 +477,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PolicyTagManagerSerializationClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -516,13 +486,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PolicyTagManagerSerializationClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/gapic_version.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/gapic_version.py index c843b7364c5d..cb24f2360f5a 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/gapic_version.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.21.0" # {x-release-please-version} +__version__ = "3.21.1" # {x-release-please-version} diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py index 1760cad85812..5610b7a2f99f 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/data_catalog/client.py @@ -598,36 +598,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataCatalogClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -637,13 +607,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataCatalogClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py index 420376ff3822..aef9c262cac6 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/policy_tag_manager/client.py @@ -489,36 +489,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PolicyTagManagerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -528,13 +498,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PolicyTagManagerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py index 179bf24456d1..25ac84fdc50f 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/services/policy_tag_manager_serialization/client.py @@ -474,36 +474,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = PolicyTagManagerSerializationClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -513,13 +483,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or PolicyTagManagerSerializationClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1.json b/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1.json index d5d949a57dd6..d2f74c49388e 100644 --- a/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1.json +++ b/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-datacatalog", - "version": "3.21.0" + "version": "3.21.1" }, "snippets": [ { diff --git a/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1beta1.json b/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1beta1.json index 19721102705f..16437f0e222d 100644 --- a/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1beta1.json +++ b/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-datacatalog", - "version": "3.21.0" + "version": "3.21.1" }, "snippets": [ { diff --git a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_data_catalog.py b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_data_catalog.py index e90c5f1e70d0..a330df809776 100644 --- a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_data_catalog.py +++ b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_data_catalog.py @@ -324,85 +324,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py index f496e975a219..972254a07769 100644 --- a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py +++ b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager.py @@ -321,85 +321,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py index f964eab46dcd..c3975dc8fb0f 100644 --- a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py +++ b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1/test_policy_tag_manager_serialization.py @@ -349,89 +349,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - PolicyTagManagerSerializationClient, - transports.PolicyTagManagerSerializationGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py index 5e2d2b936c65..bfab0c177432 100644 --- a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py +++ b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_data_catalog.py @@ -311,85 +311,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DataCatalogClient, transports.DataCatalogGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py index 57e1f17d36f0..810cb501ae32 100644 --- a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py +++ b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager.py @@ -321,85 +321,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (PolicyTagManagerClient, transports.PolicyTagManagerGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py index 903f1ec35238..ec57ea454df9 100644 --- a/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py +++ b/packages/google-cloud-datacatalog/tests/unit/gapic/datacatalog_v1beta1/test_policy_tag_manager_serialization.py @@ -348,89 +348,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - PolicyTagManagerSerializationClient, - transports.PolicyTagManagerSerializationGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataform/CHANGELOG.md b/packages/google-cloud-dataform/CHANGELOG.md index a842ff3a5021..dde302be4912 100644 --- a/packages/google-cloud-dataform/CHANGELOG.md +++ b/packages/google-cloud-dataform/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataform-v0.5.12...google-cloud-dataform-v0.5.13) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.5.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataform-v0.5.11...google-cloud-dataform-v0.5.12) (2024-10-24) diff --git a/packages/google-cloud-dataform/google/cloud/dataform/gapic_version.py b/packages/google-cloud-dataform/google/cloud/dataform/gapic_version.py index cc43a639a105..bf678492aaad 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform/gapic_version.py +++ b/packages/google-cloud-dataform/google/cloud/dataform/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.12" # {x-release-please-version} +__version__ = "0.5.13" # {x-release-please-version} diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/gapic_version.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/gapic_version.py index cc43a639a105..bf678492aaad 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/gapic_version.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.12" # {x-release-please-version} +__version__ = "0.5.13" # {x-release-please-version} diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/client.py index 1642af58d116..33da795ded13 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/client.py @@ -611,36 +611,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataformClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -650,13 +620,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataformClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1beta1.json b/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1beta1.json index b2b1fa7538fc..096b7975227d 100644 --- a/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1beta1.json +++ b/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dataform", - "version": "0.5.12" + "version": "0.5.13" }, "snippets": [ { diff --git a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1beta1/test_dataform.py b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1beta1/test_dataform.py index e57acb0c2c4c..6bf0b6f1180b 100644 --- a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1beta1/test_dataform.py +++ b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1beta1/test_dataform.py @@ -299,86 +299,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DataformClient, transports.DataformGrpcTransport, "grpc"), - (DataformClient, transports.DataformRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datalabeling/CHANGELOG.md b/packages/google-cloud-datalabeling/CHANGELOG.md index f5419aaf8955..d75319c9aee4 100644 --- a/packages/google-cloud-datalabeling/CHANGELOG.md +++ b/packages/google-cloud-datalabeling/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-datalabeling/#history +## [1.11.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datalabeling-v1.11.0...google-cloud-datalabeling-v1.11.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [1.11.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datalabeling-v1.10.5...google-cloud-datalabeling-v1.11.0) (2024-10-24) diff --git a/packages/google-cloud-datalabeling/google/cloud/datalabeling/gapic_version.py b/packages/google-cloud-datalabeling/google/cloud/datalabeling/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-datalabeling/google/cloud/datalabeling/gapic_version.py +++ b/packages/google-cloud-datalabeling/google/cloud/datalabeling/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-datalabeling/google/cloud/datalabeling_v1beta1/gapic_version.py b/packages/google-cloud-datalabeling/google/cloud/datalabeling_v1beta1/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-datalabeling/google/cloud/datalabeling_v1beta1/gapic_version.py +++ b/packages/google-cloud-datalabeling/google/cloud/datalabeling_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-datalabeling/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py b/packages/google-cloud-datalabeling/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py index 1cd66859e9ed..ff8e5242b10e 100644 --- a/packages/google-cloud-datalabeling/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py +++ b/packages/google-cloud-datalabeling/google/cloud/datalabeling_v1beta1/services/data_labeling_service/client.py @@ -621,36 +621,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataLabelingServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -660,13 +630,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataLabelingServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datalabeling/samples/generated_samples/snippet_metadata_google.cloud.datalabeling.v1beta1.json b/packages/google-cloud-datalabeling/samples/generated_samples/snippet_metadata_google.cloud.datalabeling.v1beta1.json index f9b2f3ab241c..de5f79447163 100644 --- a/packages/google-cloud-datalabeling/samples/generated_samples/snippet_metadata_google.cloud.datalabeling.v1beta1.json +++ b/packages/google-cloud-datalabeling/samples/generated_samples/snippet_metadata_google.cloud.datalabeling.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-datalabeling", - "version": "1.11.0" + "version": "1.11.1" }, "snippets": [ { diff --git a/packages/google-cloud-datalabeling/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py b/packages/google-cloud-datalabeling/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py index 19c3ca7020d9..634bca8e777b 100644 --- a/packages/google-cloud-datalabeling/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py +++ b/packages/google-cloud-datalabeling/tests/unit/gapic/datalabeling_v1beta1/test_data_labeling_service.py @@ -357,89 +357,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - DataLabelingServiceClient, - transports.DataLabelingServiceGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataplex/CHANGELOG.md b/packages/google-cloud-dataplex/CHANGELOG.md index 204b9589e081..36d8806cd8cd 100644 --- a/packages/google-cloud-dataplex/CHANGELOG.md +++ b/packages/google-cloud-dataplex/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [2.3.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataplex-v2.3.0...google-cloud-dataplex-v2.3.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [2.3.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataplex-v2.2.2...google-cloud-dataplex-v2.3.0) (2024-10-24) diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex/gapic_version.py b/packages/google-cloud-dataplex/google/cloud/dataplex/gapic_version.py index 38b74a960221..dd79fdad215c 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex/gapic_version.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.3.0" # {x-release-please-version} +__version__ = "2.3.1" # {x-release-please-version} diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/gapic_version.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/gapic_version.py index 38b74a960221..dd79fdad215c 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/gapic_version.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.3.0" # {x-release-please-version} +__version__ = "2.3.1" # {x-release-please-version} diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/client.py index 953065ec8f72..6c5aeb8272cf 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/client.py @@ -547,36 +547,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CatalogServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -586,13 +556,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CatalogServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/content_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/content_service/client.py index 931da4dd7e72..5b521dda8a55 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/content_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/content_service/client.py @@ -492,36 +492,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ContentServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -531,13 +501,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ContentServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/client.py index ab52839b7c22..03f256f07fdc 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/client.py @@ -530,36 +530,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataScanServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -569,13 +539,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataScanServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/client.py index 560cbd8e541c..e42d1677cd1d 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/client.py @@ -520,36 +520,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataTaxonomyServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -559,13 +529,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataTaxonomyServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/client.py index 97a0c4ef7f95..5e488a12b5fa 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/client.py @@ -653,36 +653,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataplexServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -692,13 +662,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataplexServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/client.py index 932feff8afd7..8ada13d7743b 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/client.py @@ -525,36 +525,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = MetadataServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -564,13 +534,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or MetadataServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataplex/samples/generated_samples/snippet_metadata_google.cloud.dataplex.v1.json b/packages/google-cloud-dataplex/samples/generated_samples/snippet_metadata_google.cloud.dataplex.v1.json index d441efaa45ce..e466410d1430 100644 --- a/packages/google-cloud-dataplex/samples/generated_samples/snippet_metadata_google.cloud.dataplex.v1.json +++ b/packages/google-cloud-dataplex/samples/generated_samples/snippet_metadata_google.cloud.dataplex.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dataplex", - "version": "2.3.0" + "version": "2.3.1" }, "snippets": [ { diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_catalog_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_catalog_service.py index 6d11066066e2..6198538a8234 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_catalog_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_catalog_service.py @@ -331,85 +331,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_content_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_content_service.py index 29fa13129c99..3f618ec57c6c 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_content_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_content_service.py @@ -323,85 +323,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ContentServiceClient, transports.ContentServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_scan_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_scan_service.py index b7e0f9a54d5f..ada3a77c02bd 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_scan_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_scan_service.py @@ -337,85 +337,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DataScanServiceClient, transports.DataScanServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_taxonomy_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_taxonomy_service.py index 899af08114ae..cbe00d789c16 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_taxonomy_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_taxonomy_service.py @@ -347,89 +347,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - DataTaxonomyServiceClient, - transports.DataTaxonomyServiceGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_dataplex_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_dataplex_service.py index 2e3867d1ded6..4f51ecd23937 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_dataplex_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_dataplex_service.py @@ -331,85 +331,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DataplexServiceClient, transports.DataplexServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_metadata_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_metadata_service.py index 47cb77d2d6c1..7c4bfd0cb98b 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_metadata_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_metadata_service.py @@ -319,85 +319,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (MetadataServiceClient, transports.MetadataServiceGrpcTransport, "grpc"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataproc/CHANGELOG.md b/packages/google-cloud-dataproc/CHANGELOG.md index 8e0835c419cf..ca882977e9c1 100644 --- a/packages/google-cloud-dataproc/CHANGELOG.md +++ b/packages/google-cloud-dataproc/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-dataproc/#history +## [5.15.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataproc-v5.15.0...google-cloud-dataproc-v5.15.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [5.15.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataproc-v5.14.0...google-cloud-dataproc-v5.15.0) (2024-10-24) diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc/gapic_version.py b/packages/google-cloud-dataproc/google/cloud/dataproc/gapic_version.py index d3fb1e059462..2f51a6ead321 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc/gapic_version.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "5.15.0" # {x-release-please-version} +__version__ = "5.15.1" # {x-release-please-version} diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/gapic_version.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/gapic_version.py index d3fb1e059462..2f51a6ead321 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/gapic_version.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "5.15.0" # {x-release-please-version} +__version__ = "5.15.1" # {x-release-please-version} diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/autoscaling_policy_service/client.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/autoscaling_policy_service/client.py index cf8936541353..102389445efc 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/autoscaling_policy_service/client.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/autoscaling_policy_service/client.py @@ -469,36 +469,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = AutoscalingPolicyServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -508,13 +478,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or AutoscalingPolicyServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/batch_controller/client.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/batch_controller/client.py index 06b9494a2bb0..2ad7f3e9a226 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/batch_controller/client.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/batch_controller/client.py @@ -492,36 +492,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = BatchControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -531,13 +501,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or BatchControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/cluster_controller/client.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/cluster_controller/client.py index f3ec1e754250..72c70fec8614 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/cluster_controller/client.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/cluster_controller/client.py @@ -541,36 +541,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ClusterControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -580,13 +550,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ClusterControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/job_controller/client.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/job_controller/client.py index 9e80a67a3462..8883a6b45141 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/job_controller/client.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/job_controller/client.py @@ -443,36 +443,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = JobControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -482,13 +452,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or JobControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/node_group_controller/client.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/node_group_controller/client.py index 5a09ceff3b7a..131f8090a81c 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/node_group_controller/client.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/node_group_controller/client.py @@ -470,36 +470,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = NodeGroupControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -509,13 +479,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or NodeGroupControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/session_controller/client.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/session_controller/client.py index 4cf598a22ef2..2c7196b6b50f 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/session_controller/client.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/session_controller/client.py @@ -514,36 +514,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SessionControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -553,13 +523,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SessionControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/session_template_controller/client.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/session_template_controller/client.py index 5c7bb34e4c62..48408f697fc2 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/session_template_controller/client.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/session_template_controller/client.py @@ -492,36 +492,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = SessionTemplateControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -531,13 +501,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or SessionTemplateControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/workflow_template_service/client.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/workflow_template_service/client.py index 61d8feb58149..7101f26dfaeb 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/workflow_template_service/client.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/services/workflow_template_service/client.py @@ -544,36 +544,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = WorkflowTemplateServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -583,13 +553,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or WorkflowTemplateServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dataproc/samples/generated_samples/snippet_metadata_google.cloud.dataproc.v1.json b/packages/google-cloud-dataproc/samples/generated_samples/snippet_metadata_google.cloud.dataproc.v1.json index ff1df21529fc..f8466cf79500 100644 --- a/packages/google-cloud-dataproc/samples/generated_samples/snippet_metadata_google.cloud.dataproc.v1.json +++ b/packages/google-cloud-dataproc/samples/generated_samples/snippet_metadata_google.cloud.dataproc.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dataproc", - "version": "5.15.0" + "version": "5.15.1" }, "snippets": [ { diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_autoscaling_policy_service.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_autoscaling_policy_service.py index 2087042eedb6..f4c91d0398a0 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_autoscaling_policy_service.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_autoscaling_policy_service.py @@ -340,94 +340,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - AutoscalingPolicyServiceClient, - transports.AutoscalingPolicyServiceGrpcTransport, - "grpc", - ), - ( - AutoscalingPolicyServiceClient, - transports.AutoscalingPolicyServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_batch_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_batch_controller.py index 8d900d427aee..a673847575e7 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_batch_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_batch_controller.py @@ -333,86 +333,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (BatchControllerClient, transports.BatchControllerGrpcTransport, "grpc"), - (BatchControllerClient, transports.BatchControllerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py index 45b17a9df888..3593271f8a30 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py @@ -345,86 +345,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ClusterControllerClient, transports.ClusterControllerGrpcTransport, "grpc"), - (ClusterControllerClient, transports.ClusterControllerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_job_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_job_controller.py index 037ade1da6bc..1bb3f821daf7 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_job_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_job_controller.py @@ -329,86 +329,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (JobControllerClient, transports.JobControllerGrpcTransport, "grpc"), - (JobControllerClient, transports.JobControllerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py index 5004a273b763..fe3d749bb3c0 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py @@ -346,94 +346,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - NodeGroupControllerClient, - transports.NodeGroupControllerGrpcTransport, - "grpc", - ), - ( - NodeGroupControllerClient, - transports.NodeGroupControllerRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_session_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_session_controller.py index 7c6ab36a253e..1fbded365565 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_session_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_session_controller.py @@ -342,86 +342,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (SessionControllerClient, transports.SessionControllerGrpcTransport, "grpc"), - (SessionControllerClient, transports.SessionControllerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_session_template_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_session_template_controller.py index ff8b8c23cbcf..51e8a7cfcd54 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_session_template_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_session_template_controller.py @@ -345,94 +345,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - SessionTemplateControllerClient, - transports.SessionTemplateControllerGrpcTransport, - "grpc", - ), - ( - SessionTemplateControllerClient, - transports.SessionTemplateControllerRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py index bb1918825cc8..b738e59cf64a 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py @@ -351,94 +351,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - WorkflowTemplateServiceClient, - transports.WorkflowTemplateServiceGrpcTransport, - "grpc", - ), - ( - WorkflowTemplateServiceClient, - transports.WorkflowTemplateServiceRestTransport, - "rest", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datastream/CHANGELOG.md b/packages/google-cloud-datastream/CHANGELOG.md index 214844bee18a..c667a26e014f 100644 --- a/packages/google-cloud-datastream/CHANGELOG.md +++ b/packages/google-cloud-datastream/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datastream-v1.10.0...google-cloud-datastream-v1.10.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [1.10.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datastream-v1.9.5...google-cloud-datastream-v1.10.0) (2024-10-24) diff --git a/packages/google-cloud-datastream/google/cloud/datastream/gapic_version.py b/packages/google-cloud-datastream/google/cloud/datastream/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-datastream/google/cloud/datastream/gapic_version.py +++ b/packages/google-cloud-datastream/google/cloud/datastream/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-datastream/google/cloud/datastream_v1/gapic_version.py b/packages/google-cloud-datastream/google/cloud/datastream_v1/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-datastream/google/cloud/datastream_v1/gapic_version.py +++ b/packages/google-cloud-datastream/google/cloud/datastream_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-datastream/google/cloud/datastream_v1/services/datastream/client.py b/packages/google-cloud-datastream/google/cloud/datastream_v1/services/datastream/client.py index 853071962115..77e8053b60a5 100644 --- a/packages/google-cloud-datastream/google/cloud/datastream_v1/services/datastream/client.py +++ b/packages/google-cloud-datastream/google/cloud/datastream_v1/services/datastream/client.py @@ -580,36 +580,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DatastreamClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -619,13 +589,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DatastreamClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datastream/google/cloud/datastream_v1alpha1/gapic_version.py b/packages/google-cloud-datastream/google/cloud/datastream_v1alpha1/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-datastream/google/cloud/datastream_v1alpha1/gapic_version.py +++ b/packages/google-cloud-datastream/google/cloud/datastream_v1alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-datastream/google/cloud/datastream_v1alpha1/services/datastream/client.py b/packages/google-cloud-datastream/google/cloud/datastream_v1alpha1/services/datastream/client.py index ce57716e9865..8dbe4ed4fee1 100644 --- a/packages/google-cloud-datastream/google/cloud/datastream_v1alpha1/services/datastream/client.py +++ b/packages/google-cloud-datastream/google/cloud/datastream_v1alpha1/services/datastream/client.py @@ -533,36 +533,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DatastreamClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -572,13 +542,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DatastreamClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-datastream/samples/generated_samples/snippet_metadata_google.cloud.datastream.v1.json b/packages/google-cloud-datastream/samples/generated_samples/snippet_metadata_google.cloud.datastream.v1.json index 2a6eeafecdcd..e51156316e2e 100644 --- a/packages/google-cloud-datastream/samples/generated_samples/snippet_metadata_google.cloud.datastream.v1.json +++ b/packages/google-cloud-datastream/samples/generated_samples/snippet_metadata_google.cloud.datastream.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-datastream", - "version": "1.10.0" + "version": "1.10.1" }, "snippets": [ { diff --git a/packages/google-cloud-datastream/samples/generated_samples/snippet_metadata_google.cloud.datastream.v1alpha1.json b/packages/google-cloud-datastream/samples/generated_samples/snippet_metadata_google.cloud.datastream.v1alpha1.json index 03f40cfcd6e8..e83ae9de83b6 100644 --- a/packages/google-cloud-datastream/samples/generated_samples/snippet_metadata_google.cloud.datastream.v1alpha1.json +++ b/packages/google-cloud-datastream/samples/generated_samples/snippet_metadata_google.cloud.datastream.v1alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-datastream", - "version": "1.10.0" + "version": "1.10.1" }, "snippets": [ { diff --git a/packages/google-cloud-datastream/tests/unit/gapic/datastream_v1/test_datastream.py b/packages/google-cloud-datastream/tests/unit/gapic/datastream_v1/test_datastream.py index 20c3591b1848..600b3f7f4da1 100644 --- a/packages/google-cloud-datastream/tests/unit/gapic/datastream_v1/test_datastream.py +++ b/packages/google-cloud-datastream/tests/unit/gapic/datastream_v1/test_datastream.py @@ -313,86 +313,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DatastreamClient, transports.DatastreamGrpcTransport, "grpc"), - (DatastreamClient, transports.DatastreamRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-datastream/tests/unit/gapic/datastream_v1alpha1/test_datastream.py b/packages/google-cloud-datastream/tests/unit/gapic/datastream_v1alpha1/test_datastream.py index 7f7967c89b17..ff611a29f85d 100644 --- a/packages/google-cloud-datastream/tests/unit/gapic/datastream_v1alpha1/test_datastream.py +++ b/packages/google-cloud-datastream/tests/unit/gapic/datastream_v1alpha1/test_datastream.py @@ -309,86 +309,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DatastreamClient, transports.DatastreamGrpcTransport, "grpc"), - (DatastreamClient, transports.DatastreamRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-deploy/CHANGELOG.md b/packages/google-cloud-deploy/CHANGELOG.md index 74c3e8e5d684..c621fef6afee 100644 --- a/packages/google-cloud-deploy/CHANGELOG.md +++ b/packages/google-cloud-deploy/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [2.3.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-deploy-v2.2.0...google-cloud-deploy-v2.3.0) (2024-10-31) + + +### Features + +* added new fields for the Automation Repair rule ([5bad720](https://github.com/googleapis/google-cloud-python/commit/5bad72013c2ad2727bdf3628454437e2047b2c9b)) +* added route destination related fields to Gateway service mesh message ([5bad720](https://github.com/googleapis/google-cloud-python/commit/5bad72013c2ad2727bdf3628454437e2047b2c9b)) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [2.2.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-deploy-v2.1.0...google-cloud-deploy-v2.2.0) (2024-10-24) diff --git a/packages/google-cloud-deploy/google/cloud/deploy/__init__.py b/packages/google-cloud-deploy/google/cloud/deploy/__init__.py index 4b051017ed31..e4cc21aeab87 100644 --- a/packages/google-cloud-deploy/google/cloud/deploy/__init__.py +++ b/packages/google-cloud-deploy/google/cloud/deploy/__init__.py @@ -36,6 +36,7 @@ AnthosCluster, ApproveRolloutRequest, ApproveRolloutResponse, + AssociatedEntities, Automation, AutomationResourceSelector, AutomationRolloutMetadata, @@ -144,13 +145,16 @@ Release, RenderMetadata, RepairPhase, + RepairPhaseConfig, RepairRolloutOperation, RepairRolloutRule, RepairState, + Retry, RetryAttempt, RetryJobRequest, RetryJobResponse, RetryPhase, + Rollback, RollbackAttempt, RollbackTargetConfig, RollbackTargetRequest, @@ -226,6 +230,7 @@ "AnthosCluster", "ApproveRolloutRequest", "ApproveRolloutResponse", + "AssociatedEntities", "Automation", "AutomationResourceSelector", "AutomationRolloutMetadata", @@ -333,12 +338,15 @@ "Release", "RenderMetadata", "RepairPhase", + "RepairPhaseConfig", "RepairRolloutOperation", "RepairRolloutRule", + "Retry", "RetryAttempt", "RetryJobRequest", "RetryJobResponse", "RetryPhase", + "Rollback", "RollbackAttempt", "RollbackTargetConfig", "RollbackTargetRequest", diff --git a/packages/google-cloud-deploy/google/cloud/deploy/gapic_version.py b/packages/google-cloud-deploy/google/cloud/deploy/gapic_version.py index 04f353585881..38b74a960221 100644 --- a/packages/google-cloud-deploy/google/cloud/deploy/gapic_version.py +++ b/packages/google-cloud-deploy/google/cloud/deploy/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.2.0" # {x-release-please-version} +__version__ = "2.3.0" # {x-release-please-version} diff --git a/packages/google-cloud-deploy/google/cloud/deploy_v1/__init__.py b/packages/google-cloud-deploy/google/cloud/deploy_v1/__init__.py index c9c4ecd71f25..1c2b034046fb 100644 --- a/packages/google-cloud-deploy/google/cloud/deploy_v1/__init__.py +++ b/packages/google-cloud-deploy/google/cloud/deploy_v1/__init__.py @@ -33,6 +33,7 @@ AnthosCluster, ApproveRolloutRequest, ApproveRolloutResponse, + AssociatedEntities, Automation, AutomationResourceSelector, AutomationRolloutMetadata, @@ -141,13 +142,16 @@ Release, RenderMetadata, RepairPhase, + RepairPhaseConfig, RepairRolloutOperation, RepairRolloutRule, RepairState, + Retry, RetryAttempt, RetryJobRequest, RetryJobResponse, RetryPhase, + Rollback, RollbackAttempt, RollbackTargetConfig, RollbackTargetRequest, @@ -208,6 +212,7 @@ "AnthosCluster", "ApproveRolloutRequest", "ApproveRolloutResponse", + "AssociatedEntities", "Automation", "AutomationEvent", "AutomationResourceSelector", @@ -326,13 +331,16 @@ "ReleaseRenderEvent", "RenderMetadata", "RepairPhase", + "RepairPhaseConfig", "RepairRolloutOperation", "RepairRolloutRule", "RepairState", + "Retry", "RetryAttempt", "RetryJobRequest", "RetryJobResponse", "RetryPhase", + "Rollback", "RollbackAttempt", "RollbackTargetConfig", "RollbackTargetRequest", diff --git a/packages/google-cloud-deploy/google/cloud/deploy_v1/gapic_version.py b/packages/google-cloud-deploy/google/cloud/deploy_v1/gapic_version.py index 04f353585881..38b74a960221 100644 --- a/packages/google-cloud-deploy/google/cloud/deploy_v1/gapic_version.py +++ b/packages/google-cloud-deploy/google/cloud/deploy_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.2.0" # {x-release-please-version} +__version__ = "2.3.0" # {x-release-please-version} diff --git a/packages/google-cloud-deploy/google/cloud/deploy_v1/services/cloud_deploy/client.py b/packages/google-cloud-deploy/google/cloud/deploy_v1/services/cloud_deploy/client.py index 0f24eaa59285..011e05bafe54 100644 --- a/packages/google-cloud-deploy/google/cloud/deploy_v1/services/cloud_deploy/client.py +++ b/packages/google-cloud-deploy/google/cloud/deploy_v1/services/cloud_deploy/client.py @@ -843,36 +843,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudDeployClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -882,13 +852,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudDeployClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-deploy/google/cloud/deploy_v1/types/__init__.py b/packages/google-cloud-deploy/google/cloud/deploy_v1/types/__init__.py index 7017500e27c7..baf15d3a4001 100644 --- a/packages/google-cloud-deploy/google/cloud/deploy_v1/types/__init__.py +++ b/packages/google-cloud-deploy/google/cloud/deploy_v1/types/__init__.py @@ -27,6 +27,7 @@ AnthosCluster, ApproveRolloutRequest, ApproveRolloutResponse, + AssociatedEntities, Automation, AutomationResourceSelector, AutomationRolloutMetadata, @@ -135,13 +136,16 @@ Release, RenderMetadata, RepairPhase, + RepairPhaseConfig, RepairRolloutOperation, RepairRolloutRule, RepairState, + Retry, RetryAttempt, RetryJobRequest, RetryJobResponse, RetryPhase, + Rollback, RollbackAttempt, RollbackTargetConfig, RollbackTargetRequest, @@ -199,6 +203,7 @@ "AnthosCluster", "ApproveRolloutRequest", "ApproveRolloutResponse", + "AssociatedEntities", "Automation", "AutomationResourceSelector", "AutomationRolloutMetadata", @@ -306,12 +311,15 @@ "Release", "RenderMetadata", "RepairPhase", + "RepairPhaseConfig", "RepairRolloutOperation", "RepairRolloutRule", + "Retry", "RetryAttempt", "RetryJobRequest", "RetryJobResponse", "RetryPhase", + "Rollback", "RollbackAttempt", "RollbackTargetConfig", "RollbackTargetRequest", diff --git a/packages/google-cloud-deploy/google/cloud/deploy_v1/types/cloud_deploy.py b/packages/google-cloud-deploy/google/cloud/deploy_v1/types/cloud_deploy.py index 7eed27b03034..d84d4966c326 100644 --- a/packages/google-cloud-deploy/google/cloud/deploy_v1/types/cloud_deploy.py +++ b/packages/google-cloud-deploy/google/cloud/deploy_v1/types/cloud_deploy.py @@ -67,6 +67,7 @@ "CloudRunLocation", "MultiTarget", "CustomTarget", + "AssociatedEntities", "ListTargetsRequest", "ListTargetsResponse", "GetTargetRequest", @@ -164,6 +165,9 @@ "PromoteReleaseRule", "AdvanceRolloutRule", "RepairRolloutRule", + "RepairPhaseConfig", + "Retry", + "Rollback", "AutomationRuleCondition", "CreateAutomationRequest", "UpdateAutomationRequest", @@ -783,8 +787,48 @@ class GatewayServiceMesh(proto.Message): Pods for the Deployment and Service resources. This label must already be present in both resources. + route_destinations (google.cloud.deploy_v1.types.KubernetesConfig.GatewayServiceMesh.RouteDestinations): + Optional. Route destinations allow + configuring the Gateway API HTTPRoute to be + deployed to additional clusters. This option is + available for multi-cluster service mesh set ups + that require the route to exist in the clusters + that call the service. If unspecified, the + HTTPRoute will only be deployed to the Target + cluster. """ + class RouteDestinations(proto.Message): + r"""Information about route destinations for the Gateway API + service mesh. + + Attributes: + destination_ids (MutableSequence[str]): + Required. The clusters where the Gateway API + HTTPRoute resource will be deployed to. Valid + entries include the associated entities IDs + configured in the Target resource and "@self" to + include the Target cluster. + propagate_service (bool): + Optional. Whether to propagate the Kubernetes + Service to the route destination clusters. The + Service will always be deployed to the Target + cluster even if the HTTPRoute is not. This + option may be used to facilitiate successful DNS + lookup in the route destination clusters. Can + only be set to true if destinations are + specified. + """ + + destination_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + propagate_service: bool = proto.Field( + proto.BOOL, + number=2, + ) + http_route: str = proto.Field( proto.STRING, number=1, @@ -811,6 +855,13 @@ class GatewayServiceMesh(proto.Message): proto.STRING, number=6, ) + route_destinations: "KubernetesConfig.GatewayServiceMesh.RouteDestinations" = ( + proto.Field( + proto.MESSAGE, + number=8, + message="KubernetesConfig.GatewayServiceMesh.RouteDestinations", + ) + ) class ServiceNetworking(proto.Message): r"""Information about the Kubernetes Service networking @@ -1540,6 +1591,17 @@ class Target(proto.Message): Target. This field is a member of `oneof`_ ``deployment_target``. + associated_entities (MutableMapping[str, google.cloud.deploy_v1.types.AssociatedEntities]): + Optional. Map of entity IDs to their associated entities. + Associated entities allows specifying places other than the + deployment target for specific features. For example, the + Gateway API canary can be configured to deploy the HTTPRoute + to a different cluster(s) than the deployment cluster using + associated entities. An entity ID must consist of lower-case + letters, numbers, and hyphens, start with a letter and end + with a letter or a number, and have a max length of 63 + characters. In other words, it must match the following + regex: ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. etag (str): Optional. This checksum is computed by the server based on the value of other fields, and @@ -1630,6 +1692,12 @@ class Target(proto.Message): oneof="deployment_target", message="CustomTarget", ) + associated_entities: MutableMapping[str, "AssociatedEntities"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=23, + message="AssociatedEntities", + ) etag: str = proto.Field( proto.STRING, number=12, @@ -1923,6 +1991,30 @@ class CustomTarget(proto.Message): ) +class AssociatedEntities(proto.Message): + r"""Information about entities associated with a ``Target``. + + Attributes: + gke_clusters (MutableSequence[google.cloud.deploy_v1.types.GkeCluster]): + Optional. Information specifying GKE clusters + as associated entities. + anthos_clusters (MutableSequence[google.cloud.deploy_v1.types.AnthosCluster]): + Optional. Information specifying Anthos + clusters as associated entities. + """ + + gke_clusters: MutableSequence["GkeCluster"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="GkeCluster", + ) + anthos_clusters: MutableSequence["AnthosCluster"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="AnthosCluster", + ) + + class ListTargetsRequest(proto.Message): r"""The request object for ``ListTargets``. @@ -4403,6 +4495,9 @@ class Rollout(proto.Message): rolled_back_by_rollouts (MutableSequence[str]): Output only. Names of ``Rollouts`` that rolled back this ``Rollout``. + active_repair_automation_run (str): + Output only. The AutomationRun actively + repairing the rollout. """ class ApprovalState(proto.Enum): @@ -4607,6 +4702,10 @@ class FailureCause(proto.Enum): proto.STRING, number=27, ) + active_repair_automation_run: str = proto.Field( + proto.STRING, + number=28, + ) class Metadata(proto.Message): @@ -6547,6 +6646,15 @@ class RepairRolloutRule(proto.Message): Required. ID of the rule. This id must be unique in the ``Automation`` resource to which this rule belongs. The format is ``[a-z]([a-z0-9-]{0,61}[a-z0-9])?``. + phases (MutableSequence[str]): + Optional. Phases within which jobs are subject to automatic + repair actions on failure. Proceeds only after phase name + matched any one in the list, or for all phases if + unspecified. This value must consist of lower-case letters, + numbers, and hyphens, start with a letter and end with a + letter or a number, and have a max length of 63 characters. + In other words, it must match the following regex: + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. jobs (MutableSequence[str]): Optional. Jobs to repair. Proceeds only after job name matched any one in the list, or for all jobs if unspecified @@ -6559,12 +6667,19 @@ class RepairRolloutRule(proto.Message): condition (google.cloud.deploy_v1.types.AutomationRuleCondition): Output only. Information around the state of the 'Automation' rule. + repair_phases (MutableSequence[google.cloud.deploy_v1.types.RepairPhaseConfig]): + Required. Defines the types of automatic + repair phases for failed jobs. """ id: str = proto.Field( proto.STRING, number=1, ) + phases: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) jobs: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=3, @@ -6574,6 +6689,102 @@ class RepairRolloutRule(proto.Message): number=6, message="AutomationRuleCondition", ) + repair_phases: MutableSequence["RepairPhaseConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="RepairPhaseConfig", + ) + + +class RepairPhaseConfig(proto.Message): + r"""Configuration of the repair phase. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + retry (google.cloud.deploy_v1.types.Retry): + Optional. Retries a failed job. + + This field is a member of `oneof`_ ``repair_phase``. + rollback (google.cloud.deploy_v1.types.Rollback): + Optional. Rolls back a ``Rollout``. + + This field is a member of `oneof`_ ``repair_phase``. + """ + + retry: "Retry" = proto.Field( + proto.MESSAGE, + number=1, + oneof="repair_phase", + message="Retry", + ) + rollback: "Rollback" = proto.Field( + proto.MESSAGE, + number=2, + oneof="repair_phase", + message="Rollback", + ) + + +class Retry(proto.Message): + r"""Retries the failed job. + + Attributes: + attempts (int): + Required. Total number of retries. Retry is + skipped if set to 0; The minimum value is 1, and + the maximum value is 10. + wait (google.protobuf.duration_pb2.Duration): + Optional. How long to wait for the first + retry. Default is 0, and the maximum value is + 14d. + backoff_mode (google.cloud.deploy_v1.types.BackoffMode): + Optional. The pattern of how wait time will be increased. + Default is linear. Backoff mode will be ignored if ``wait`` + is 0. + """ + + attempts: int = proto.Field( + proto.INT64, + number=1, + ) + wait: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + backoff_mode: "BackoffMode" = proto.Field( + proto.ENUM, + number=3, + enum="BackoffMode", + ) + + +class Rollback(proto.Message): + r"""Rolls back a ``Rollout``. + + Attributes: + destination_phase (str): + Optional. The starting phase ID for the ``Rollout``. If + unspecified, the ``Rollout`` will start in the stable phase. + disable_rollback_if_rollout_pending (bool): + Optional. If pending rollout exists on the + target, the rollback operation will be aborted. + """ + + destination_phase: str = proto.Field( + proto.STRING, + number=1, + ) + disable_rollback_if_rollout_pending: bool = proto.Field( + proto.BOOL, + number=2, + ) class AutomationRuleCondition(proto.Message): @@ -7158,6 +7369,9 @@ class RepairRolloutOperation(proto.Message): rollout (str): Output only. The name of the rollout that initiates the ``AutomationRun``. + current_repair_phase_index (int): + Output only. The index of the current repair + action in the repair sequence. repair_phases (MutableSequence[google.cloud.deploy_v1.types.RepairPhase]): Output only. Records of the repair attempts. Each repair phase may have multiple retry @@ -7174,6 +7388,10 @@ class RepairRolloutOperation(proto.Message): proto.STRING, number=1, ) + current_repair_phase_index: int = proto.Field( + proto.INT64, + number=6, + ) repair_phases: MutableSequence["RepairPhase"] = proto.RepeatedField( proto.MESSAGE, number=3, @@ -7312,6 +7530,9 @@ class RollbackAttempt(proto.Message): state_desc (str): Output only. Description of the state of the Rollback. + disable_rollback_if_rollout_pending (bool): + Output only. If active rollout exists on the + target, abort this rollback. """ destination_phase: str = proto.Field( @@ -7331,6 +7552,10 @@ class RollbackAttempt(proto.Message): proto.STRING, number=4, ) + disable_rollback_if_rollout_pending: bool = proto.Field( + proto.BOOL, + number=5, + ) class ListAutomationRunsRequest(proto.Message): diff --git a/packages/google-cloud-deploy/samples/generated_samples/snippet_metadata_google.cloud.deploy.v1.json b/packages/google-cloud-deploy/samples/generated_samples/snippet_metadata_google.cloud.deploy.v1.json index c85274a3d0f2..8be081b739aa 100644 --- a/packages/google-cloud-deploy/samples/generated_samples/snippet_metadata_google.cloud.deploy.v1.json +++ b/packages/google-cloud-deploy/samples/generated_samples/snippet_metadata_google.cloud.deploy.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-deploy", - "version": "2.2.0" + "version": "2.3.0" }, "snippets": [ { diff --git a/packages/google-cloud-deploy/tests/unit/gapic/deploy_v1/test_cloud_deploy.py b/packages/google-cloud-deploy/tests/unit/gapic/deploy_v1/test_cloud_deploy.py index d8dc87560e05..3eac3f76854a 100644 --- a/packages/google-cloud-deploy/tests/unit/gapic/deploy_v1/test_cloud_deploy.py +++ b/packages/google-cloud-deploy/tests/unit/gapic/deploy_v1/test_cloud_deploy.py @@ -320,86 +320,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CloudDeployClient, transports.CloudDeployGrpcTransport, "grpc"), - (CloudDeployClient, transports.CloudDeployRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ @@ -12395,6 +12315,7 @@ def test_get_rollout(request_type, transport: str = "grpc"): controller_rollout="controller_rollout_value", rollback_of_rollout="rollback_of_rollout_value", rolled_back_by_rollouts=["rolled_back_by_rollouts_value"], + active_repair_automation_run="active_repair_automation_run_value", ) response = client.get_rollout(request) @@ -12422,6 +12343,7 @@ def test_get_rollout(request_type, transport: str = "grpc"): assert response.controller_rollout == "controller_rollout_value" assert response.rollback_of_rollout == "rollback_of_rollout_value" assert response.rolled_back_by_rollouts == ["rolled_back_by_rollouts_value"] + assert response.active_repair_automation_run == "active_repair_automation_run_value" def test_get_rollout_non_empty_request_with_auto_populated_field(): @@ -12560,6 +12482,7 @@ async def test_get_rollout_async( controller_rollout="controller_rollout_value", rollback_of_rollout="rollback_of_rollout_value", rolled_back_by_rollouts=["rolled_back_by_rollouts_value"], + active_repair_automation_run="active_repair_automation_run_value", ) ) response = await client.get_rollout(request) @@ -12588,6 +12511,7 @@ async def test_get_rollout_async( assert response.controller_rollout == "controller_rollout_value" assert response.rollback_of_rollout == "rollback_of_rollout_value" assert response.rolled_back_by_rollouts == ["rolled_back_by_rollouts_value"] + assert response.active_repair_automation_run == "active_repair_automation_run_value" @pytest.mark.asyncio @@ -29824,6 +29748,7 @@ async def test_get_rollout_empty_call_grpc_asyncio(): controller_rollout="controller_rollout_value", rollback_of_rollout="rollback_of_rollout_value", rolled_back_by_rollouts=["rolled_back_by_rollouts_value"], + active_repair_automation_run="active_repair_automation_run_value", ) ) await client.get_rollout(request=None) @@ -30597,6 +30522,13 @@ def test_create_delivery_pipeline_rest_call_success(request_type): }, "stable_cutback_duration": {}, "pod_selector_label": "pod_selector_label_value", + "route_destinations": { + "destination_ids": [ + "destination_ids_value1", + "destination_ids_value2", + ], + "propagate_service": True, + }, }, "service_networking": { "service": "service_value", @@ -30891,6 +30823,13 @@ def test_update_delivery_pipeline_rest_call_success(request_type): }, "stable_cutback_duration": {}, "pod_selector_label": "pod_selector_label_value", + "route_destinations": { + "destination_ids": [ + "destination_ids_value1", + "destination_ids_value2", + ], + "propagate_service": True, + }, }, "service_networking": { "service": "service_value", @@ -31645,6 +31584,7 @@ def test_create_target_rest_call_success(request_type): "run": {"location": "location_value"}, "multi_target": {"target_ids": ["target_ids_value1", "target_ids_value2"]}, "custom_target": {"custom_target_type": "custom_target_type_value"}, + "associated_entities": {}, "etag": "etag_value", "execution_configs": [ { @@ -31870,6 +31810,7 @@ def test_update_target_rest_call_success(request_type): "run": {"location": "location_value"}, "multi_target": {"target_ids": ["target_ids_value1", "target_ids_value2"]}, "custom_target": {"custom_target_type": "custom_target_type_value"}, + "associated_entities": {}, "etag": "etag_value", "execution_configs": [ { @@ -33319,6 +33260,13 @@ def test_create_release_rest_call_success(request_type): }, "stable_cutback_duration": {}, "pod_selector_label": "pod_selector_label_value", + "route_destinations": { + "destination_ids": [ + "destination_ids_value1", + "destination_ids_value2", + ], + "propagate_service": True, + }, }, "service_networking": { "service": "service_value", @@ -33412,6 +33360,7 @@ def test_create_release_rest_call_success(request_type): "target_ids": ["target_ids_value1", "target_ids_value2"] }, "custom_target": {"custom_target_type": "custom_target_type_value"}, + "associated_entities": {}, "etag": "etag_value", "execution_configs": [ { @@ -35130,6 +35079,7 @@ def test_get_rollout_rest_call_success(request_type): controller_rollout="controller_rollout_value", rollback_of_rollout="rollback_of_rollout_value", rolled_back_by_rollouts=["rolled_back_by_rollouts_value"], + active_repair_automation_run="active_repair_automation_run_value", ) # Wrap the value into a proper Response obj @@ -35161,6 +35111,7 @@ def test_get_rollout_rest_call_success(request_type): assert response.controller_rollout == "controller_rollout_value" assert response.rollback_of_rollout == "rollback_of_rollout_value" assert response.rolled_back_by_rollouts == ["rolled_back_by_rollouts_value"] + assert response.active_repair_automation_run == "active_repair_automation_run_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -35335,6 +35286,7 @@ def test_create_rollout_rest_call_success(request_type): "rolled_back_by_rollouts_value1", "rolled_back_by_rollouts_value2", ], + "active_repair_automation_run": "active_repair_automation_run_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 @@ -36289,8 +36241,18 @@ def test_create_automation_rest_call_success(request_type): }, "repair_rollout_rule": { "id": "id_value", + "phases": ["phases_value1", "phases_value2"], "jobs": ["jobs_value1", "jobs_value2"], "condition": {}, + "repair_phases": [ + { + "retry": {"attempts": 882, "wait": {}, "backoff_mode": 1}, + "rollback": { + "destination_phase": "destination_phase_value", + "disable_rollback_if_rollout_pending": True, + }, + } + ], }, } ], @@ -36523,8 +36485,18 @@ def test_update_automation_rest_call_success(request_type): }, "repair_rollout_rule": { "id": "id_value", + "phases": ["phases_value1", "phases_value2"], "jobs": ["jobs_value1", "jobs_value2"], "condition": {}, + "repair_phases": [ + { + "retry": {"attempts": 882, "wait": {}, "backoff_mode": 1}, + "rollback": { + "destination_phase": "destination_phase_value", + "disable_rollback_if_rollout_pending": True, + }, + } + ], }, } ], diff --git a/packages/google-cloud-developerconnect/CHANGELOG.md b/packages/google-cloud-developerconnect/CHANGELOG.md index d55ffcd1edf3..0b9124561b18 100644 --- a/packages/google-cloud-developerconnect/CHANGELOG.md +++ b/packages/google-cloud-developerconnect/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-developerconnect-v0.1.3...google-cloud-developerconnect-v0.1.4) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([53c951e](https://github.com/googleapis/google-cloud-python/commit/53c951e90ad1d702fa507495532086d5d2f6b3c0)) + ## [0.1.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-developerconnect-v0.1.2...google-cloud-developerconnect-v0.1.3) (2024-10-24) diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect/gapic_version.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect/gapic_version.py index 114e40645800..937ede8823ef 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect/gapic_version.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.3" # {x-release-please-version} +__version__ = "0.1.4" # {x-release-please-version} diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/gapic_version.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/gapic_version.py index 114e40645800..937ede8823ef 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/gapic_version.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.3" # {x-release-please-version} +__version__ = "0.1.4" # {x-release-please-version} diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/client.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/client.py index 844c446da73b..3fb61f46972c 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/client.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/client.py @@ -517,36 +517,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DeveloperConnectClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -556,13 +526,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DeveloperConnectClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/snippet_metadata_google.cloud.developerconnect.v1.json b/packages/google-cloud-developerconnect/samples/generated_samples/snippet_metadata_google.cloud.developerconnect.v1.json index 7f840565943c..020e6f209525 100644 --- a/packages/google-cloud-developerconnect/samples/generated_samples/snippet_metadata_google.cloud.developerconnect.v1.json +++ b/packages/google-cloud-developerconnect/samples/generated_samples/snippet_metadata_google.cloud.developerconnect.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-developerconnect", - "version": "0.1.3" + "version": "0.1.4" }, "snippets": [ { diff --git a/packages/google-cloud-developerconnect/tests/unit/gapic/developerconnect_v1/test_developer_connect.py b/packages/google-cloud-developerconnect/tests/unit/gapic/developerconnect_v1/test_developer_connect.py index f0b2007e96f0..c94e697b442d 100644 --- a/packages/google-cloud-developerconnect/tests/unit/gapic/developerconnect_v1/test_developer_connect.py +++ b/packages/google-cloud-developerconnect/tests/unit/gapic/developerconnect_v1/test_developer_connect.py @@ -333,86 +333,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (DeveloperConnectClient, transports.DeveloperConnectGrpcTransport, "grpc"), - (DeveloperConnectClient, transports.DeveloperConnectRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-discoveryengine/CHANGELOG.md b/packages/google-cloud-discoveryengine/CHANGELOG.md index a9e80f2b33d9..01bece4eb679 100644 --- a/packages/google-cloud-discoveryengine/CHANGELOG.md +++ b/packages/google-cloud-discoveryengine/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## [0.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-discoveryengine-v0.13.2...google-cloud-discoveryengine-v0.13.3) (2024-10-31) + + +### Features + +* Add AdvancedCompleteQuery API ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Add BillingEstimation in data store ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Add GroundedGenerationService API ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Add lite search API to allow public website search with API key ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Add one_box_page_size on search ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Add Sitemap APIs to preview channel ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Support advanced boost search ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Support Google Workspace search ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Support natural language understanding search ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* support query regex in control match rules ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* Support search personalization to preview channel ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) + + +### Documentation + +* deprecate asynchronous mode in answer generation ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* deprecate extractive_answers in answer generation ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) +* keep the API doc up-to-date with recent changes ([fc70893](https://github.com/googleapis/google-cloud-python/commit/fc708935dda0102226e83dbf6cff992f1bf21373)) + ## [0.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-discoveryengine-v0.13.1...google-cloud-discoveryengine-v0.13.2) (2024-10-28) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/__init__.py index 48c89d24d6f4..0710faa2b9f8 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/__init__.py @@ -151,6 +151,8 @@ SuggestionDenyListEntry, ) from google.cloud.discoveryengine_v1beta.types.completion_service import ( + AdvancedCompleteQueryRequest, + AdvancedCompleteQueryResponse, CompleteQueryRequest, CompleteQueryResponse, ) @@ -192,7 +194,12 @@ from google.cloud.discoveryengine_v1beta.types.custom_tuning_model import ( CustomTuningModel, ) -from google.cloud.discoveryengine_v1beta.types.data_store import DataStore, LanguageInfo +from google.cloud.discoveryengine_v1beta.types.data_store import ( + DataStore, + LanguageInfo, + NaturalLanguageQueryUnderstandingConfig, + WorkspaceConfig, +) from google.cloud.discoveryengine_v1beta.types.data_store_service import ( CreateDataStoreMetadata, CreateDataStoreRequest, @@ -250,8 +257,15 @@ CheckGroundingRequest, CheckGroundingResponse, CheckGroundingSpec, + GenerateGroundedContentRequest, + GenerateGroundedContentResponse, + GroundedGenerationContent, +) +from google.cloud.discoveryengine_v1beta.types.grounding import ( + FactChunk, + GroundingConfig, + GroundingFact, ) -from google.cloud.discoveryengine_v1beta.types.grounding import FactChunk, GroundingFact from google.cloud.discoveryengine_v1beta.types.import_config import ( AlloyDbSource, BigQuerySource, @@ -358,6 +372,7 @@ ) from google.cloud.discoveryengine_v1beta.types.session import Query, Session from google.cloud.discoveryengine_v1beta.types.site_search_engine import ( + Sitemap, SiteSearchEngine, SiteVerificationInfo, TargetSite, @@ -369,8 +384,12 @@ BatchVerifyTargetSitesMetadata, BatchVerifyTargetSitesRequest, BatchVerifyTargetSitesResponse, + CreateSitemapMetadata, + CreateSitemapRequest, CreateTargetSiteMetadata, CreateTargetSiteRequest, + DeleteSitemapMetadata, + DeleteSitemapRequest, DeleteTargetSiteMetadata, DeleteTargetSiteRequest, DisableAdvancedSiteSearchMetadata, @@ -381,6 +400,8 @@ EnableAdvancedSiteSearchResponse, FetchDomainVerificationStatusRequest, FetchDomainVerificationStatusResponse, + FetchSitemapsRequest, + FetchSitemapsResponse, GetSiteSearchEngineRequest, GetTargetSiteRequest, ListTargetSitesRequest, @@ -459,6 +480,8 @@ "SolutionType", "CompletionSuggestion", "SuggestionDenyListEntry", + "AdvancedCompleteQueryRequest", + "AdvancedCompleteQueryResponse", "CompleteQueryRequest", "CompleteQueryResponse", "Condition", @@ -494,6 +517,8 @@ "CustomTuningModel", "DataStore", "LanguageInfo", + "NaturalLanguageQueryUnderstandingConfig", + "WorkspaceConfig", "CreateDataStoreMetadata", "CreateDataStoreRequest", "DeleteDataStoreMetadata", @@ -538,7 +563,11 @@ "CheckGroundingRequest", "CheckGroundingResponse", "CheckGroundingSpec", + "GenerateGroundedContentRequest", + "GenerateGroundedContentResponse", + "GroundedGenerationContent", "FactChunk", + "GroundingConfig", "GroundingFact", "AlloyDbSource", "BigQuerySource", @@ -624,6 +653,7 @@ "UpdateServingConfigRequest", "Query", "Session", + "Sitemap", "SiteSearchEngine", "SiteVerificationInfo", "TargetSite", @@ -633,8 +663,12 @@ "BatchVerifyTargetSitesMetadata", "BatchVerifyTargetSitesRequest", "BatchVerifyTargetSitesResponse", + "CreateSitemapMetadata", + "CreateSitemapRequest", "CreateTargetSiteMetadata", "CreateTargetSiteRequest", + "DeleteSitemapMetadata", + "DeleteSitemapRequest", "DeleteTargetSiteMetadata", "DeleteTargetSiteRequest", "DisableAdvancedSiteSearchMetadata", @@ -645,6 +679,8 @@ "EnableAdvancedSiteSearchResponse", "FetchDomainVerificationStatusRequest", "FetchDomainVerificationStatusResponse", + "FetchSitemapsRequest", + "FetchSitemapsResponse", "GetSiteSearchEngineRequest", "GetTargetSiteRequest", "ListTargetSitesRequest", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py index 7c2bb87c0a10..ec706d99f689 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.13.2" # {x-release-please-version} +__version__ = "0.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py index 7c2bb87c0a10..ec706d99f689 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.13.2" # {x-release-please-version} +__version__ = "0.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py index 7c2bb87c0a10..ec706d99f689 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.13.2" # {x-release-please-version} +__version__ = "0.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/__init__.py index c469dab86a26..c07b93c13971 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/__init__.py @@ -88,7 +88,12 @@ UserInfo, ) from .types.completion import CompletionSuggestion, SuggestionDenyListEntry -from .types.completion_service import CompleteQueryRequest, CompleteQueryResponse +from .types.completion_service import ( + AdvancedCompleteQueryRequest, + AdvancedCompleteQueryResponse, + CompleteQueryRequest, + CompleteQueryResponse, +) from .types.control import Condition, Control from .types.control_service import ( CreateControlRequest, @@ -125,7 +130,12 @@ UpdateSessionRequest, ) from .types.custom_tuning_model import CustomTuningModel -from .types.data_store import DataStore, LanguageInfo +from .types.data_store import ( + DataStore, + LanguageInfo, + NaturalLanguageQueryUnderstandingConfig, + WorkspaceConfig, +) from .types.data_store_service import ( CreateDataStoreMetadata, CreateDataStoreRequest, @@ -178,8 +188,11 @@ CheckGroundingRequest, CheckGroundingResponse, CheckGroundingSpec, + GenerateGroundedContentRequest, + GenerateGroundedContentResponse, + GroundedGenerationContent, ) -from .types.grounding import FactChunk, GroundingFact +from .types.grounding import FactChunk, GroundingConfig, GroundingFact from .types.import_config import ( AlloyDbSource, BigQuerySource, @@ -272,7 +285,12 @@ UpdateServingConfigRequest, ) from .types.session import Query, Session -from .types.site_search_engine import SiteSearchEngine, SiteVerificationInfo, TargetSite +from .types.site_search_engine import ( + Sitemap, + SiteSearchEngine, + SiteVerificationInfo, + TargetSite, +) from .types.site_search_engine_service import ( BatchCreateTargetSiteMetadata, BatchCreateTargetSitesRequest, @@ -280,8 +298,12 @@ BatchVerifyTargetSitesMetadata, BatchVerifyTargetSitesRequest, BatchVerifyTargetSitesResponse, + CreateSitemapMetadata, + CreateSitemapRequest, CreateTargetSiteMetadata, CreateTargetSiteRequest, + DeleteSitemapMetadata, + DeleteSitemapRequest, DeleteTargetSiteMetadata, DeleteTargetSiteRequest, DisableAdvancedSiteSearchMetadata, @@ -292,6 +314,8 @@ EnableAdvancedSiteSearchResponse, FetchDomainVerificationStatusRequest, FetchDomainVerificationStatusResponse, + FetchSitemapsRequest, + FetchSitemapsResponse, GetSiteSearchEngineRequest, GetTargetSiteRequest, ListTargetSitesRequest, @@ -334,6 +358,8 @@ "ServingConfigServiceAsyncClient", "SiteSearchEngineServiceAsyncClient", "UserEventServiceAsyncClient", + "AdvancedCompleteQueryRequest", + "AdvancedCompleteQueryResponse", "AlloyDbSource", "Answer", "AnswerQueryRequest", @@ -383,6 +409,8 @@ "CreateSchemaMetadata", "CreateSchemaRequest", "CreateSessionRequest", + "CreateSitemapMetadata", + "CreateSitemapRequest", "CreateTargetSiteMetadata", "CreateTargetSiteRequest", "CustomAttribute", @@ -401,6 +429,8 @@ "DeleteSchemaMetadata", "DeleteSchemaRequest", "DeleteSessionRequest", + "DeleteSitemapMetadata", + "DeleteSitemapRequest", "DeleteTargetSiteMetadata", "DeleteTargetSiteRequest", "DisableAdvancedSiteSearchMetadata", @@ -422,9 +452,13 @@ "FactChunk", "FetchDomainVerificationStatusRequest", "FetchDomainVerificationStatusResponse", + "FetchSitemapsRequest", + "FetchSitemapsResponse", "FhirStoreSource", "FirestoreSource", "GcsSource", + "GenerateGroundedContentRequest", + "GenerateGroundedContentResponse", "GetAnswerRequest", "GetControlRequest", "GetConversationRequest", @@ -439,7 +473,9 @@ "GetSessionRequest", "GetSiteSearchEngineRequest", "GetTargetSiteRequest", + "GroundedGenerationContent", "GroundedGenerationServiceClient", + "GroundingConfig", "GroundingFact", "ImportCompletionSuggestionsMetadata", "ImportCompletionSuggestionsRequest", @@ -489,6 +525,7 @@ "ListTargetSitesRequest", "ListTargetSitesResponse", "MediaInfo", + "NaturalLanguageQueryUnderstandingConfig", "PageInfo", "PanelInfo", "PauseEngineRequest", @@ -543,6 +580,7 @@ "SiteSearchEngine", "SiteSearchEngineServiceClient", "SiteVerificationInfo", + "Sitemap", "SolutionType", "SpannerSource", "SuggestionDenyListEntry", @@ -571,5 +609,6 @@ "UserEvent", "UserEventServiceClient", "UserInfo", + "WorkspaceConfig", "WriteUserEventRequest", ) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_metadata.json b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_metadata.json index 02ac1aa251d2..4ac5fd41e110 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_metadata.json +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_metadata.json @@ -10,6 +10,11 @@ "grpc": { "libraryClient": "CompletionServiceClient", "rpcs": { + "AdvancedCompleteQuery": { + "methods": [ + "advanced_complete_query" + ] + }, "CompleteQuery": { "methods": [ "complete_query" @@ -40,6 +45,11 @@ "grpc-async": { "libraryClient": "CompletionServiceAsyncClient", "rpcs": { + "AdvancedCompleteQuery": { + "methods": [ + "advanced_complete_query" + ] + }, "CompleteQuery": { "methods": [ "complete_query" @@ -70,6 +80,11 @@ "rest": { "libraryClient": "CompletionServiceClient", "rpcs": { + "AdvancedCompleteQuery": { + "methods": [ + "advanced_complete_query" + ] + }, "CompleteQuery": { "methods": [ "complete_query" @@ -867,6 +882,16 @@ "methods": [ "check_grounding" ] + }, + "GenerateGroundedContent": { + "methods": [ + "generate_grounded_content" + ] + }, + "StreamGenerateGroundedContent": { + "methods": [ + "stream_generate_grounded_content" + ] } } }, @@ -877,6 +902,16 @@ "methods": [ "check_grounding" ] + }, + "GenerateGroundedContent": { + "methods": [ + "generate_grounded_content" + ] + }, + "StreamGenerateGroundedContent": { + "methods": [ + "stream_generate_grounded_content" + ] } } }, @@ -887,6 +922,16 @@ "methods": [ "check_grounding" ] + }, + "GenerateGroundedContent": { + "methods": [ + "generate_grounded_content" + ] + }, + "StreamGenerateGroundedContent": { + "methods": [ + "stream_generate_grounded_content" + ] } } } @@ -1300,6 +1345,11 @@ "methods": [ "search" ] + }, + "SearchLite": { + "methods": [ + "search_lite" + ] } } }, @@ -1310,6 +1360,11 @@ "methods": [ "search" ] + }, + "SearchLite": { + "methods": [ + "search_lite" + ] } } }, @@ -1320,6 +1375,11 @@ "methods": [ "search" ] + }, + "SearchLite": { + "methods": [ + "search_lite" + ] } } } @@ -1453,11 +1513,21 @@ "batch_verify_target_sites" ] }, + "CreateSitemap": { + "methods": [ + "create_sitemap" + ] + }, "CreateTargetSite": { "methods": [ "create_target_site" ] }, + "DeleteSitemap": { + "methods": [ + "delete_sitemap" + ] + }, "DeleteTargetSite": { "methods": [ "delete_target_site" @@ -1478,6 +1548,11 @@ "fetch_domain_verification_status" ] }, + "FetchSitemaps": { + "methods": [ + "fetch_sitemaps" + ] + }, "GetSiteSearchEngine": { "methods": [ "get_site_search_engine" @@ -1518,11 +1593,21 @@ "batch_verify_target_sites" ] }, + "CreateSitemap": { + "methods": [ + "create_sitemap" + ] + }, "CreateTargetSite": { "methods": [ "create_target_site" ] }, + "DeleteSitemap": { + "methods": [ + "delete_sitemap" + ] + }, "DeleteTargetSite": { "methods": [ "delete_target_site" @@ -1543,6 +1628,11 @@ "fetch_domain_verification_status" ] }, + "FetchSitemaps": { + "methods": [ + "fetch_sitemaps" + ] + }, "GetSiteSearchEngine": { "methods": [ "get_site_search_engine" @@ -1583,11 +1673,21 @@ "batch_verify_target_sites" ] }, + "CreateSitemap": { + "methods": [ + "create_sitemap" + ] + }, "CreateTargetSite": { "methods": [ "create_target_site" ] }, + "DeleteSitemap": { + "methods": [ + "delete_sitemap" + ] + }, "DeleteTargetSite": { "methods": [ "delete_target_site" @@ -1608,6 +1708,11 @@ "fetch_domain_verification_status" ] }, + "FetchSitemaps": { + "methods": [ + "fetch_sitemaps" + ] + }, "GetSiteSearchEngine": { "methods": [ "get_site_search_engine" diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py index 7c2bb87c0a10..ec706d99f689 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.13.2" # {x-release-please-version} +__version__ = "0.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py index 11aa00e43d28..f71c4a4ce933 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py @@ -70,8 +70,16 @@ class CompletionServiceAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = CompletionServiceClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = CompletionServiceClient._DEFAULT_UNIVERSE + completion_config_path = staticmethod( + CompletionServiceClient.completion_config_path + ) + parse_completion_config_path = staticmethod( + CompletionServiceClient.parse_completion_config_path + ) data_store_path = staticmethod(CompletionServiceClient.data_store_path) parse_data_store_path = staticmethod(CompletionServiceClient.parse_data_store_path) + document_path = staticmethod(CompletionServiceClient.document_path) + parse_document_path = staticmethod(CompletionServiceClient.parse_document_path) common_billing_account_path = staticmethod( CompletionServiceClient.common_billing_account_path ) @@ -356,6 +364,98 @@ async def sample_complete_query(): # Done; return the response. return response + async def advanced_complete_query( + self, + request: Optional[ + Union[completion_service.AdvancedCompleteQueryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.AdvancedCompleteQueryResponse: + r"""Completes the user input with advanced keyword + suggestions. + + .. 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 discoveryengine_v1beta + + async def sample_advanced_complete_query(): + # Create a client + client = discoveryengine_v1beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.AdvancedCompleteQueryRequest( + completion_config="completion_config_value", + query="query_value", + ) + + # Make the request + response = await client.advanced_complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest, dict]]): + The request object. Request message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. . + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse: + Response message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. + + """ + # 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, completion_service.AdvancedCompleteQueryRequest): + request = completion_service.AdvancedCompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.advanced_complete_query + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("completion_config", request.completion_config),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def import_suggestion_deny_list_entries( self, request: Optional[ diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/client.py index cb3840e0b367..6e320bb9a94a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/client.py @@ -191,6 +191,28 @@ def transport(self) -> CompletionServiceTransport: """ return self._transport + @staticmethod + def completion_config_path( + project: str, + location: str, + data_store: str, + ) -> str: + """Returns a fully-qualified completion_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/completionConfig".format( + project=project, + location=location, + data_store=data_store, + ) + + @staticmethod + def parse_completion_config_path(path: str) -> Dict[str, str]: + """Parses a completion_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/completionConfig$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def data_store_path( project: str, @@ -213,6 +235,32 @@ def parse_data_store_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def document_path( + project: str, + location: str, + data_store: str, + branch: str, + document: str, + ) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format( + project=project, + location=location, + data_store=data_store, + branch=branch, + document=document, + ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str, str]: + """Parses a document path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -778,6 +826,96 @@ def sample_complete_query(): # Done; return the response. return response + def advanced_complete_query( + self, + request: Optional[ + Union[completion_service.AdvancedCompleteQueryRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.AdvancedCompleteQueryResponse: + r"""Completes the user input with advanced keyword + suggestions. + + .. 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 discoveryengine_v1beta + + def sample_advanced_complete_query(): + # Create a client + client = discoveryengine_v1beta.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.AdvancedCompleteQueryRequest( + completion_config="completion_config_value", + query="query_value", + ) + + # Make the request + response = client.advanced_complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest, dict]): + The request object. Request message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. . + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse: + Response message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. + + """ + # 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, completion_service.AdvancedCompleteQueryRequest): + request = completion_service.AdvancedCompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.advanced_complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("completion_config", request.completion_config),) + ), + ) + + # 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 import_suggestion_deny_list_entries( self, request: Optional[ diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py index 5dfcc895b1cc..d7aabb17cbe5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py @@ -139,6 +139,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.advanced_complete_query: gapic_v1.method.wrap_method( + self.advanced_complete_query, + default_timeout=None, + client_info=client_info, + ), self.import_suggestion_deny_list_entries: gapic_v1.method.wrap_method( self.import_suggestion_deny_list_entries, default_timeout=None, @@ -202,6 +207,18 @@ def complete_query( ]: raise NotImplementedError() + @property + def advanced_complete_query( + self, + ) -> Callable[ + [completion_service.AdvancedCompleteQueryRequest], + Union[ + completion_service.AdvancedCompleteQueryResponse, + Awaitable[completion_service.AdvancedCompleteQueryResponse], + ], + ]: + raise NotImplementedError() + @property def import_suggestion_deny_list_entries( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py index 4203bdf050a1..7415f83eab0c 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py @@ -285,6 +285,36 @@ def complete_query( ) return self._stubs["complete_query"] + @property + def advanced_complete_query( + self, + ) -> Callable[ + [completion_service.AdvancedCompleteQueryRequest], + completion_service.AdvancedCompleteQueryResponse, + ]: + r"""Return a callable for the advanced complete query method over gRPC. + + Completes the user input with advanced keyword + suggestions. + + Returns: + Callable[[~.AdvancedCompleteQueryRequest], + ~.AdvancedCompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "advanced_complete_query" not in self._stubs: + self._stubs["advanced_complete_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.CompletionService/AdvancedCompleteQuery", + request_serializer=completion_service.AdvancedCompleteQueryRequest.serialize, + response_deserializer=completion_service.AdvancedCompleteQueryResponse.deserialize, + ) + return self._stubs["advanced_complete_query"] + @property def import_suggestion_deny_list_entries( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py index daab244b166b..5c0eaffb442e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py @@ -295,6 +295,36 @@ def complete_query( ) return self._stubs["complete_query"] + @property + def advanced_complete_query( + self, + ) -> Callable[ + [completion_service.AdvancedCompleteQueryRequest], + Awaitable[completion_service.AdvancedCompleteQueryResponse], + ]: + r"""Return a callable for the advanced complete query method over gRPC. + + Completes the user input with advanced keyword + suggestions. + + Returns: + Callable[[~.AdvancedCompleteQueryRequest], + Awaitable[~.AdvancedCompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "advanced_complete_query" not in self._stubs: + self._stubs["advanced_complete_query"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.CompletionService/AdvancedCompleteQuery", + request_serializer=completion_service.AdvancedCompleteQueryRequest.serialize, + response_deserializer=completion_service.AdvancedCompleteQueryResponse.deserialize, + ) + return self._stubs["advanced_complete_query"] + @property def import_suggestion_deny_list_entries( self, @@ -435,6 +465,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.advanced_complete_query: self._wrap_method( + self.advanced_complete_query, + default_timeout=None, + client_info=client_info, + ), self.import_suggestion_deny_list_entries: self._wrap_method( self.import_suggestion_deny_list_entries, default_timeout=None, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py index 3647d42c1fbe..1f3e39a540f9 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py @@ -66,6 +66,14 @@ class CompletionServiceRestInterceptor: .. code-block:: python class MyCustomCompletionServiceInterceptor(CompletionServiceRestInterceptor): + def pre_advanced_complete_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_advanced_complete_query(self, response): + logging.log(f"Received response: {response}") + return response + def pre_complete_query(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -112,6 +120,31 @@ def post_purge_suggestion_deny_list_entries(self, response): """ + def pre_advanced_complete_query( + self, + request: completion_service.AdvancedCompleteQueryRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + completion_service.AdvancedCompleteQueryRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for advanced_complete_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService server. + """ + return request, metadata + + def post_advanced_complete_query( + self, response: completion_service.AdvancedCompleteQueryResponse + ) -> completion_service.AdvancedCompleteQueryResponse: + """Post-rpc interceptor for advanced_complete_query + + Override in a subclass to manipulate the response + after it is returned by the CompletionService server but before + it is returned to user code. + """ + return response + def pre_complete_query( self, request: completion_service.CompleteQueryRequest, @@ -554,6 +587,110 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client + class _AdvancedCompleteQuery( + _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery, + CompletionServiceRestStub, + ): + def __hash__(self): + return hash("CompletionServiceRestTransport.AdvancedCompleteQuery") + + @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: completion_service.AdvancedCompleteQueryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.AdvancedCompleteQueryResponse: + r"""Call the advanced complete query method over HTTP. + + Args: + request (~.completion_service.AdvancedCompleteQueryRequest): + The request object. Request message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. . + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.completion_service.AdvancedCompleteQueryResponse: + Response message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. + + """ + + http_options = ( + _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery._get_http_options() + ) + request, metadata = self._interceptor.pre_advanced_complete_query( + request, metadata + ) + transcoded_request = _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery._get_transcoded_request( + http_options, request + ) + + body = _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery._get_query_params_json( + transcoded_request + ) + + # Send the request + response = ( + CompletionServiceRestTransport._AdvancedCompleteQuery._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 = completion_service.AdvancedCompleteQueryResponse() + pb_resp = completion_service.AdvancedCompleteQueryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_advanced_complete_query(resp) + return resp + class _CompleteQuery( _BaseCompletionServiceRestTransport._BaseCompleteQuery, CompletionServiceRestStub, @@ -1060,6 +1197,17 @@ def __call__( resp = self._interceptor.post_purge_suggestion_deny_list_entries(resp) return resp + @property + def advanced_complete_query( + self, + ) -> Callable[ + [completion_service.AdvancedCompleteQueryRequest], + completion_service.AdvancedCompleteQueryResponse, + ]: + # 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._AdvancedCompleteQuery(self._session, self._host, self._interceptor) # type: ignore + @property def complete_query( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest_base.py index c8f7c9f92be9..d1dac581b318 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest_base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest_base.py @@ -93,6 +93,73 @@ def __init__( api_audience=api_audience, ) + class _BaseAdvancedCompleteQuery: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{completion_config=projects/*/locations/*/dataStores/*/completionConfig}:completeQuery", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{completion_config=projects/*/locations/*/collections/*/dataStores/*/completionConfig}:completeQuery", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{completion_config=projects/*/locations/*/collections/*/engines/*/completionConfig}:completeQuery", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = completion_service.AdvancedCompleteQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCompleteQuery: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/async_client.py index 763f8bbd5deb..ac09cc7367a0 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/async_client.py @@ -326,9 +326,9 @@ async def sample_create_control(): parent (:class:`str`): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`` or - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}``. + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -457,7 +457,7 @@ async def sample_delete_control(): name (:class:`str`): Required. The resource name of the Control to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -690,7 +690,7 @@ async def sample_get_control(): name (:class:`str`): Required. The resource name of the Control to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -800,9 +800,9 @@ async def sample_list_controls(): The request object. Request for ListControls method. parent (:class:`str`): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`` or - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}``. + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/client.py index 4a323d2871fc..ff98c2d42f8e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/control_service/client.py @@ -771,9 +771,9 @@ def sample_create_control(): parent (str): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`` or - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}``. + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -899,7 +899,7 @@ def sample_delete_control(): name (str): Required. The resource name of the Control to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1126,7 +1126,7 @@ def sample_get_control(): name (str): Required. The resource name of the Control to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1233,9 +1233,9 @@ def sample_list_controls(): The request object. Request for ListControls method. parent (str): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`` or - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}``. + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py index d3580b5a7a9d..fc97f1a30d6a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py @@ -357,9 +357,9 @@ async def sample_converse_conversation(): name (:class:`str`): Required. The resource name of the Conversation to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` to activate auto session mode, which automatically creates a new conversation inside a ConverseConversation session. @@ -486,7 +486,7 @@ async def sample_create_conversation(): parent (:class:`str`): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -605,7 +605,7 @@ async def sample_delete_conversation(): name (:class:`str`): Required. The resource name of the Conversation to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -835,7 +835,7 @@ async def sample_get_conversation(): name (:class:`str`): Required. The resource name of the Conversation to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -946,7 +946,7 @@ async def sample_list_conversations(): The request object. Request for ListConversations method. parent (:class:`str`): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1164,7 +1164,7 @@ async def sample_get_answer(): name (:class:`str`): Required. The resource name of the Answer to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/engines/{engine_id}/sessions/{session_id}/answers/{answer_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine_id}/sessions/{session_id}/answers/{answer_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1274,7 +1274,7 @@ async def sample_create_session(): parent (:class:`str`): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1387,7 +1387,7 @@ async def sample_delete_session(): name (:class:`str`): Required. The resource name of the Session to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1610,7 +1610,7 @@ async def sample_get_session(): name (:class:`str`): Required. The resource name of the Session to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1717,7 +1717,7 @@ async def sample_list_sessions(): The request object. Request for ListSessions method. parent (:class:`str`): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py index 9ad776314f29..d4b8f77c4b7c 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py @@ -907,9 +907,9 @@ def sample_converse_conversation(): name (str): Required. The resource name of the Conversation to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` to activate auto session mode, which automatically creates a new conversation inside a ConverseConversation session. @@ -1033,7 +1033,7 @@ def sample_create_conversation(): parent (str): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1149,7 +1149,7 @@ def sample_delete_conversation(): name (str): Required. The resource name of the Conversation to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1373,7 +1373,7 @@ def sample_get_conversation(): name (str): Required. The resource name of the Conversation to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1481,7 +1481,7 @@ def sample_list_conversations(): The request object. Request for ListConversations method. parent (str): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1694,7 +1694,7 @@ def sample_get_answer(): name (str): Required. The resource name of the Answer to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/engines/{engine_id}/sessions/{session_id}/answers/{answer_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine_id}/sessions/{session_id}/answers/{answer_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1801,7 +1801,7 @@ def sample_create_session(): parent (str): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1911,7 +1911,7 @@ def sample_delete_session(): name (str): Required. The resource name of the Session to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2128,7 +2128,7 @@ def sample_get_session(): name (str): Required. The resource name of the Session to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2232,7 +2232,7 @@ def sample_list_sessions(): The request object. Request for ListSessions method. parent (str): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py index 099bdb1db5fb..7967e8c72032 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py @@ -83,6 +83,10 @@ class DocumentServiceAsyncClient: parse_branch_path = staticmethod(DocumentServiceClient.parse_branch_path) document_path = staticmethod(DocumentServiceClient.document_path) parse_document_path = staticmethod(DocumentServiceClient.parse_document_path) + fhir_resource_path = staticmethod(DocumentServiceClient.fhir_resource_path) + parse_fhir_resource_path = staticmethod( + DocumentServiceClient.parse_fhir_resource_path + ) fhir_store_path = staticmethod(DocumentServiceClient.fhir_store_path) parse_fhir_store_path = staticmethod(DocumentServiceClient.parse_fhir_store_path) common_billing_account_path = staticmethod( diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/client.py index becc34d592cc..22b3cfbf61bd 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/document_service/client.py @@ -250,6 +250,34 @@ def parse_document_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def fhir_resource_path( + project: str, + location: str, + dataset: str, + fhir_store: str, + resource_type: str, + fhir_resource_id: str, + ) -> str: + """Returns a fully-qualified fhir_resource string.""" + return "projects/{project}/locations/{location}/datasets/{dataset}/fhirStores/{fhir_store}/fhir/{resource_type}/{fhir_resource_id}".format( + project=project, + location=location, + dataset=dataset, + fhir_store=fhir_store, + resource_type=resource_type, + fhir_resource_id=fhir_resource_id, + ) + + @staticmethod + def parse_fhir_resource_path(path: str) -> Dict[str, str]: + """Parses a fhir_resource path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/datasets/(?P.+?)/fhirStores/(?P.+?)/fhir/(?P.+?)/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def fhir_store_path( project: str, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/async_client.py index 0de0d04f6a2e..aadbcbb9a97a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/async_client.py @@ -982,7 +982,7 @@ async def sample_pause_engine(): engine. name (:class:`str`): Required. The name of the engine to pause. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1091,7 +1091,7 @@ async def sample_resume_engine(): engine. name (:class:`str`): Required. The name of the engine to resume. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1207,7 +1207,7 @@ async def sample_tune_engine(): name (:class:`str`): Required. The resource name of the engine to tune. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/client.py index 414e3974dcab..5ce67a449a4e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/engine_service/client.py @@ -1412,7 +1412,7 @@ def sample_pause_engine(): engine. name (str): Required. The name of the engine to pause. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1518,7 +1518,7 @@ def sample_resume_engine(): engine. name (str): Required. The name of the engine to resume. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1631,7 +1631,7 @@ def sample_tune_engine(): name (str): Required. The resource name of the engine to tune. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/async_client.py index edfa4fe53e34..44b710f206ce 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/async_client.py @@ -16,6 +16,9 @@ from collections import OrderedDict import re from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, Callable, Dict, Mapping, @@ -75,6 +78,16 @@ class GroundedGenerationServiceAsyncClient: parse_grounding_config_path = staticmethod( GroundedGenerationServiceClient.parse_grounding_config_path ) + location_path = staticmethod(GroundedGenerationServiceClient.location_path) + parse_location_path = staticmethod( + GroundedGenerationServiceClient.parse_location_path + ) + serving_config_path = staticmethod( + GroundedGenerationServiceClient.serving_config_path + ) + parse_serving_config_path = staticmethod( + GroundedGenerationServiceClient.parse_serving_config_path + ) common_billing_account_path = staticmethod( GroundedGenerationServiceClient.common_billing_account_path ) @@ -275,6 +288,184 @@ def __init__( client_info=client_info, ) + def stream_generate_grounded_content( + self, + requests: Optional[ + AsyncIterator[grounded_generation_service.GenerateGroundedContentRequest] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[ + AsyncIterable[grounded_generation_service.GenerateGroundedContentResponse] + ]: + r"""Generates grounded content in a streaming fashion. + + .. 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 discoveryengine_v1beta + + async def sample_stream_generate_grounded_content(): + # Create a client + client = discoveryengine_v1beta.GroundedGenerationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GenerateGroundedContentRequest( + location="location_value", + ) + + # This method expects an iterator which contains + # 'discoveryengine_v1beta.GenerateGroundedContentRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.stream_generate_grounded_content(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest`]): + The request object AsyncIterator. Top-level message sent by the client for the + ``GenerateGroundedContent`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse]: + Response for the GenerateGroundedContent method. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.stream_generate_grounded_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + (gapic_v1.routing_header.to_grpc_metadata(()),) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_grounded_content( + self, + request: Optional[ + Union[grounded_generation_service.GenerateGroundedContentRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grounded_generation_service.GenerateGroundedContentResponse: + r"""Generates grounded content. + + .. 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 discoveryengine_v1beta + + async def sample_generate_grounded_content(): + # Create a client + client = discoveryengine_v1beta.GroundedGenerationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GenerateGroundedContentRequest( + location="location_value", + ) + + # Make the request + response = await client.generate_grounded_content(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest, dict]]): + The request object. Top-level message sent by the client for the + ``GenerateGroundedContent`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse: + Response for the GenerateGroundedContent method. + """ + # 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, grounded_generation_service.GenerateGroundedContentRequest + ): + request = grounded_generation_service.GenerateGroundedContentRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_grounded_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("location", request.location),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def check_grounding( self, request: Optional[ diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/client.py index 1e48cf12d469..1e098819e159 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/client.py @@ -19,6 +19,8 @@ from typing import ( Callable, Dict, + Iterable, + Iterator, Mapping, MutableMapping, MutableSequence, @@ -210,6 +212,47 @@ def parse_grounding_config_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def 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_location_path(path: str) -> Dict[str, str]: + """Parses a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path( + project: str, + location: str, + data_store: str, + serving_config: str, + ) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format( + project=project, + location=location, + data_store=data_store, + serving_config=serving_config, + ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str, str]: + """Parses a serving_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -691,6 +734,182 @@ def __init__( api_audience=self._client_options.api_audience, ) + def stream_generate_grounded_content( + self, + requests: Optional[ + Iterator[grounded_generation_service.GenerateGroundedContentRequest] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[grounded_generation_service.GenerateGroundedContentResponse]: + r"""Generates grounded content in a streaming fashion. + + .. 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 discoveryengine_v1beta + + def sample_stream_generate_grounded_content(): + # Create a client + client = discoveryengine_v1beta.GroundedGenerationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GenerateGroundedContentRequest( + location="location_value", + ) + + # This method expects an iterator which contains + # 'discoveryengine_v1beta.GenerateGroundedContentRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.stream_generate_grounded_content(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest]): + The request object iterator. Top-level message sent by the client for the + ``GenerateGroundedContent`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse]: + Response for the GenerateGroundedContent method. + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.stream_generate_grounded_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + (gapic_v1.routing_header.to_grpc_metadata(()),) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_grounded_content( + self, + request: Optional[ + Union[grounded_generation_service.GenerateGroundedContentRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grounded_generation_service.GenerateGroundedContentResponse: + r"""Generates grounded content. + + .. 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 discoveryengine_v1beta + + def sample_generate_grounded_content(): + # Create a client + client = discoveryengine_v1beta.GroundedGenerationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GenerateGroundedContentRequest( + location="location_value", + ) + + # Make the request + response = client.generate_grounded_content(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest, dict]): + The request object. Top-level message sent by the client for the + ``GenerateGroundedContent`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse: + Response for the GenerateGroundedContent method. + """ + # 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, grounded_generation_service.GenerateGroundedContentRequest + ): + request = grounded_generation_service.GenerateGroundedContentRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.generate_grounded_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("location", request.location),)), + ) + + # 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 check_grounding( self, request: Optional[ diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/base.py index 6435308e0888..7a389de840a2 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/base.py @@ -130,6 +130,16 @@ def host(self): def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { + self.stream_generate_grounded_content: gapic_v1.method.wrap_method( + self.stream_generate_grounded_content, + default_timeout=None, + client_info=client_info, + ), + self.generate_grounded_content: gapic_v1.method.wrap_method( + self.generate_grounded_content, + default_timeout=None, + client_info=client_info, + ), self.check_grounding: gapic_v1.method.wrap_method( self.check_grounding, default_timeout=None, @@ -161,6 +171,30 @@ def close(self): """ raise NotImplementedError() + @property + def stream_generate_grounded_content( + self, + ) -> Callable[ + [grounded_generation_service.GenerateGroundedContentRequest], + Union[ + grounded_generation_service.GenerateGroundedContentResponse, + Awaitable[grounded_generation_service.GenerateGroundedContentResponse], + ], + ]: + raise NotImplementedError() + + @property + def generate_grounded_content( + self, + ) -> Callable[ + [grounded_generation_service.GenerateGroundedContentRequest], + Union[ + grounded_generation_service.GenerateGroundedContentResponse, + Awaitable[grounded_generation_service.GenerateGroundedContentResponse], + ], + ]: + raise NotImplementedError() + @property def check_grounding( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/grpc.py index a476ed8daf46..5822ad1c78e7 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/grpc.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/grpc.py @@ -236,6 +236,67 @@ def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service.""" return self._grpc_channel + @property + def stream_generate_grounded_content( + self, + ) -> Callable[ + [grounded_generation_service.GenerateGroundedContentRequest], + grounded_generation_service.GenerateGroundedContentResponse, + ]: + r"""Return a callable for the stream generate grounded + content method over gRPC. + + Generates grounded content in a streaming fashion. + + Returns: + Callable[[~.GenerateGroundedContentRequest], + ~.GenerateGroundedContentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "stream_generate_grounded_content" not in self._stubs: + self._stubs[ + "stream_generate_grounded_content" + ] = self.grpc_channel.stream_stream( + "/google.cloud.discoveryengine.v1beta.GroundedGenerationService/StreamGenerateGroundedContent", + request_serializer=grounded_generation_service.GenerateGroundedContentRequest.serialize, + response_deserializer=grounded_generation_service.GenerateGroundedContentResponse.deserialize, + ) + return self._stubs["stream_generate_grounded_content"] + + @property + def generate_grounded_content( + self, + ) -> Callable[ + [grounded_generation_service.GenerateGroundedContentRequest], + grounded_generation_service.GenerateGroundedContentResponse, + ]: + r"""Return a callable for the generate grounded content method over gRPC. + + Generates grounded content. + + Returns: + Callable[[~.GenerateGroundedContentRequest], + ~.GenerateGroundedContentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_grounded_content" not in self._stubs: + self._stubs["generate_grounded_content"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.GroundedGenerationService/GenerateGroundedContent", + request_serializer=grounded_generation_service.GenerateGroundedContentRequest.serialize, + response_deserializer=grounded_generation_service.GenerateGroundedContentResponse.deserialize, + ) + return self._stubs["generate_grounded_content"] + @property def check_grounding( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/grpc_asyncio.py index 2b821e54c253..b0db39df6ad4 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/grpc_asyncio.py @@ -244,6 +244,67 @@ def grpc_channel(self) -> aio.Channel: # Return the channel from cache. return self._grpc_channel + @property + def stream_generate_grounded_content( + self, + ) -> Callable[ + [grounded_generation_service.GenerateGroundedContentRequest], + Awaitable[grounded_generation_service.GenerateGroundedContentResponse], + ]: + r"""Return a callable for the stream generate grounded + content method over gRPC. + + Generates grounded content in a streaming fashion. + + Returns: + Callable[[~.GenerateGroundedContentRequest], + Awaitable[~.GenerateGroundedContentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "stream_generate_grounded_content" not in self._stubs: + self._stubs[ + "stream_generate_grounded_content" + ] = self.grpc_channel.stream_stream( + "/google.cloud.discoveryengine.v1beta.GroundedGenerationService/StreamGenerateGroundedContent", + request_serializer=grounded_generation_service.GenerateGroundedContentRequest.serialize, + response_deserializer=grounded_generation_service.GenerateGroundedContentResponse.deserialize, + ) + return self._stubs["stream_generate_grounded_content"] + + @property + def generate_grounded_content( + self, + ) -> Callable[ + [grounded_generation_service.GenerateGroundedContentRequest], + Awaitable[grounded_generation_service.GenerateGroundedContentResponse], + ]: + r"""Return a callable for the generate grounded content method over gRPC. + + Generates grounded content. + + Returns: + Callable[[~.GenerateGroundedContentRequest], + Awaitable[~.GenerateGroundedContentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_grounded_content" not in self._stubs: + self._stubs["generate_grounded_content"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.GroundedGenerationService/GenerateGroundedContent", + request_serializer=grounded_generation_service.GenerateGroundedContentRequest.serialize, + response_deserializer=grounded_generation_service.GenerateGroundedContentResponse.deserialize, + ) + return self._stubs["generate_grounded_content"] + @property def check_grounding( self, @@ -276,6 +337,16 @@ def check_grounding( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { + self.stream_generate_grounded_content: self._wrap_method( + self.stream_generate_grounded_content, + default_timeout=None, + client_info=client_info, + ), + self.generate_grounded_content: self._wrap_method( + self.generate_grounded_content, + default_timeout=None, + client_info=client_info, + ), self.check_grounding: self._wrap_method( self.check_grounding, default_timeout=None, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py index aca1a6e6f209..b942a1210cbc 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest.py @@ -70,6 +70,14 @@ def post_check_grounding(self, response): logging.log(f"Received response: {response}") return response + def pre_generate_grounded_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_grounded_content(self, response): + logging.log(f"Received response: {response}") + return response + transport = GroundedGenerationServiceRestTransport(interceptor=MyCustomGroundedGenerationServiceInterceptor()) client = GroundedGenerationServiceClient(transport=transport) @@ -101,6 +109,32 @@ def post_check_grounding( """ return response + def pre_generate_grounded_content( + self, + request: grounded_generation_service.GenerateGroundedContentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + grounded_generation_service.GenerateGroundedContentRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for generate_grounded_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the GroundedGenerationService server. + """ + return request, metadata + + def post_generate_grounded_content( + self, response: grounded_generation_service.GenerateGroundedContentResponse + ) -> grounded_generation_service.GenerateGroundedContentResponse: + """Post-rpc interceptor for generate_grounded_content + + Override in a subclass to manipulate the response + after it is returned by the GroundedGenerationService server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( self, request: operations_pb2.CancelOperationRequest, @@ -359,6 +393,129 @@ def __call__( resp = self._interceptor.post_check_grounding(resp) return resp + class _GenerateGroundedContent( + _BaseGroundedGenerationServiceRestTransport._BaseGenerateGroundedContent, + GroundedGenerationServiceRestStub, + ): + def __hash__(self): + return hash( + "GroundedGenerationServiceRestTransport.GenerateGroundedContent" + ) + + @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: grounded_generation_service.GenerateGroundedContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> grounded_generation_service.GenerateGroundedContentResponse: + r"""Call the generate grounded content method over HTTP. + + Args: + request (~.grounded_generation_service.GenerateGroundedContentRequest): + The request object. Top-level message sent by the client for the + ``GenerateGroundedContent`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.grounded_generation_service.GenerateGroundedContentResponse: + Response for the ``GenerateGroundedContent`` method. + """ + + http_options = ( + _BaseGroundedGenerationServiceRestTransport._BaseGenerateGroundedContent._get_http_options() + ) + request, metadata = self._interceptor.pre_generate_grounded_content( + request, metadata + ) + transcoded_request = _BaseGroundedGenerationServiceRestTransport._BaseGenerateGroundedContent._get_transcoded_request( + http_options, request + ) + + body = _BaseGroundedGenerationServiceRestTransport._BaseGenerateGroundedContent._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGroundedGenerationServiceRestTransport._BaseGenerateGroundedContent._get_query_params_json( + transcoded_request + ) + + # Send the request + response = GroundedGenerationServiceRestTransport._GenerateGroundedContent._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 = grounded_generation_service.GenerateGroundedContentResponse() + pb_resp = grounded_generation_service.GenerateGroundedContentResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_grounded_content(resp) + return resp + + class _StreamGenerateGroundedContent( + _BaseGroundedGenerationServiceRestTransport._BaseStreamGenerateGroundedContent, + GroundedGenerationServiceRestStub, + ): + def __hash__(self): + return hash( + "GroundedGenerationServiceRestTransport.StreamGenerateGroundedContent" + ) + + def __call__( + self, + request: grounded_generation_service.GenerateGroundedContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method StreamGenerateGroundedContent is not available over REST transport" + ) + @property def check_grounding( self, @@ -370,6 +527,28 @@ def check_grounding( # In C++ this would require a dynamic_cast return self._CheckGrounding(self._session, self._host, self._interceptor) # type: ignore + @property + def generate_grounded_content( + self, + ) -> Callable[ + [grounded_generation_service.GenerateGroundedContentRequest], + grounded_generation_service.GenerateGroundedContentResponse, + ]: + # 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._GenerateGroundedContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def stream_generate_grounded_content( + self, + ) -> Callable[ + [grounded_generation_service.GenerateGroundedContentRequest], + grounded_generation_service.GenerateGroundedContentResponse, + ]: + # 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._StreamGenerateGroundedContent(self._session, self._host, self._interceptor) # type: ignore + @property def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest_base.py index fb56e71f3be4..e9f92de9ae3d 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest_base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/grounded_generation_service/transports/rest_base.py @@ -146,6 +146,69 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGenerateGroundedContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{location=projects/*/locations/*}:generateGroundedContent", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = grounded_generation_service.GenerateGroundedContentRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGroundedGenerationServiceRestTransport._BaseGenerateGroundedContent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStreamGenerateGroundedContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + class _BaseCancelOperation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py index 56ce313b2922..9fe464fbe5b8 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py @@ -370,6 +370,123 @@ async def sample_search(): # Done; return the response. return response + async def search_lite( + self, + request: Optional[Union[search_service.SearchRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchLiteAsyncPager: + r"""Performs a search. Similar to the + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method, but a lite version that allows API key for + authentication, where OAuth and IAM checks are not required. + + Only public website search is supported by this method. If data + stores and engines not associated with public website search are + specified, a ``FAILED_PRECONDITION`` error is returned. + + This method can be used for easy onboarding without having to + implement an authentication backend. However, it is strongly + recommended to use + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + instead with required OAuth and IAM checks to provide better + data security. + + .. 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 discoveryengine_v1beta + + async def sample_search_lite(): + # Create a client + client = discoveryengine_v1beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search_lite(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.SearchRequest, dict]]): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchLiteAsyncPager: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + 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, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_lite + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("serving_config", request.serving_config),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchLiteAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/client.py index 08012f374f38..639137ad9db2 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/client.py @@ -905,6 +905,121 @@ def sample_search(): # Done; return the response. return response + def search_lite( + self, + request: Optional[Union[search_service.SearchRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchLitePager: + r"""Performs a search. Similar to the + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method, but a lite version that allows API key for + authentication, where OAuth and IAM checks are not required. + + Only public website search is supported by this method. If data + stores and engines not associated with public website search are + specified, a ``FAILED_PRECONDITION`` error is returned. + + This method can be used for easy onboarding without having to + implement an authentication backend. However, it is strongly + recommended to use + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + instead with required OAuth and IAM checks to provide better + data security. + + .. 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 discoveryengine_v1beta + + def sample_search_lite(): + # Create a client + client = discoveryengine_v1beta.SearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search_lite(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchLitePager: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + 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, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_lite] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("serving_config", request.serving_config),) + ), + ) + + # 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.SearchLitePager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "SearchServiceClient": return self diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py index e514bc8ef44a..b73f61b8dd86 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py @@ -191,3 +191,155 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchLitePager: + """A pager for iterating through ``search_lite`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchLite`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` + 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[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.SearchRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.SearchResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(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[search_service.SearchResponse]: + 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[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchLiteAsyncPager: + """A pager for iterating through ``search_lite`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchLite`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.SearchRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.SearchResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py index c091edf6223f..2a0d34437c82 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py @@ -135,6 +135,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.search_lite: gapic_v1.method.wrap_method( + self.search_lite, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: gapic_v1.method.wrap_method( self.cancel_operation, default_timeout=None, @@ -170,6 +175,15 @@ def search( ]: raise NotImplementedError() + @property + def search_lite( + self, + ) -> Callable[ + [search_service.SearchRequest], + Union[search_service.SearchResponse, Awaitable[search_service.SearchResponse]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py index 6660199c7b68..aa1334b86f48 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py @@ -262,6 +262,46 @@ def search( ) return self._stubs["search"] + @property + def search_lite( + self, + ) -> Callable[[search_service.SearchRequest], search_service.SearchResponse]: + r"""Return a callable for the search lite method over gRPC. + + Performs a search. Similar to the + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method, but a lite version that allows API key for + authentication, where OAuth and IAM checks are not required. + + Only public website search is supported by this method. If data + stores and engines not associated with public website search are + specified, a ``FAILED_PRECONDITION`` error is returned. + + This method can be used for easy onboarding without having to + implement an authentication backend. However, it is strongly + recommended to use + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + instead with required OAuth and IAM checks to provide better + data security. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_lite" not in self._stubs: + self._stubs["search_lite"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SearchService/SearchLite", + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs["search_lite"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py index 747d680113ac..918cf7437eed 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py @@ -272,6 +272,48 @@ def search( ) return self._stubs["search"] + @property + def search_lite( + self, + ) -> Callable[ + [search_service.SearchRequest], Awaitable[search_service.SearchResponse] + ]: + r"""Return a callable for the search lite method over gRPC. + + Performs a search. Similar to the + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method, but a lite version that allows API key for + authentication, where OAuth and IAM checks are not required. + + Only public website search is supported by this method. If data + stores and engines not associated with public website search are + specified, a ``FAILED_PRECONDITION`` error is returned. + + This method can be used for easy onboarding without having to + implement an authentication backend. However, it is strongly + recommended to use + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + instead with required OAuth and IAM checks to provide better + data security. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "search_lite" not in self._stubs: + self._stubs["search_lite"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SearchService/SearchLite", + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs["search_lite"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -280,6 +322,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.search_lite: self._wrap_method( + self.search_lite, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py index 7101cf839bc8..8e7e7cb195d8 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py @@ -70,6 +70,14 @@ def post_search(self, response): logging.log(f"Received response: {response}") return response + def pre_search_lite(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_lite(self, response): + logging.log(f"Received response: {response}") + return response + transport = SearchServiceRestTransport(interceptor=MyCustomSearchServiceInterceptor()) client = SearchServiceClient(transport=transport) @@ -97,6 +105,27 @@ def post_search( """ return response + def pre_search_lite( + self, request: search_service.SearchRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[search_service.SearchRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_lite + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService server. + """ + return request, metadata + + def post_search_lite( + self, response: search_service.SearchResponse + ) -> search_service.SearchResponse: + """Post-rpc interceptor for search_lite + + Override in a subclass to manipulate the response + after it is returned by the SearchService server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( self, request: operations_pb2.CancelOperationRequest, @@ -352,6 +381,111 @@ def __call__( resp = self._interceptor.post_search(resp) return resp + class _SearchLite( + _BaseSearchServiceRestTransport._BaseSearchLite, SearchServiceRestStub + ): + def __hash__(self): + return hash("SearchServiceRestTransport.SearchLite") + + @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: search_service.SearchRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> search_service.SearchResponse: + r"""Call the search lite method over HTTP. + + Args: + request (~.search_service.SearchRequest): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.search_service.SearchResponse: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + """ + + http_options = ( + _BaseSearchServiceRestTransport._BaseSearchLite._get_http_options() + ) + request, metadata = self._interceptor.pre_search_lite(request, metadata) + transcoded_request = ( + _BaseSearchServiceRestTransport._BaseSearchLite._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSearchServiceRestTransport._BaseSearchLite._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSearchServiceRestTransport._BaseSearchLite._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = SearchServiceRestTransport._SearchLite._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 = search_service.SearchResponse() + pb_resp = search_service.SearchResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_lite(resp) + return resp + @property def search( self, @@ -360,6 +494,14 @@ def search( # In C++ this would require a dynamic_cast return self._Search(self._session, self._host, self._interceptor) # type: ignore + @property + def search_lite( + self, + ) -> Callable[[search_service.SearchRequest], search_service.SearchResponse]: + # 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._SearchLite(self._session, self._host, self._interceptor) # type: ignore + @property def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest_base.py index d59a673be92a..636752c6d910 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest_base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest_base.py @@ -156,6 +156,73 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseSearchLite: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:searchLite", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:searchLite", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/{serving_config=projects/*/locations/*/collections/*/engines/*/servingConfigs/*}:searchLite", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = search_service.SearchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSearchServiceRestTransport._BaseSearchLite._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCancelOperation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/async_client.py index 9a77767ae93f..418bd00e1e7c 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/async_client.py @@ -51,7 +51,7 @@ from google.cloud.discoveryengine_v1beta.types import ( serving_config as gcd_serving_config, ) -from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import common, search_service from google.cloud.discoveryengine_v1beta.types import serving_config from google.cloud.discoveryengine_v1beta.types import serving_config_service @@ -456,7 +456,7 @@ async def sample_get_serving_config(): name (:class:`str`): Required. The resource name of the ServingConfig to get. Format: - ``projects/{project_number}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -570,7 +570,7 @@ async def sample_list_serving_configs(): parent (:class:`str`): Required. Full resource name of the parent resource. Format: - ``projects/{project_number}/locations/{location}/collections/{collection}/engines/{engine}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/client.py index 355c692eab16..9fd6a3b70b16 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/serving_config_service/client.py @@ -57,7 +57,7 @@ from google.cloud.discoveryengine_v1beta.types import ( serving_config as gcd_serving_config, ) -from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import common, search_service from google.cloud.discoveryengine_v1beta.types import serving_config from google.cloud.discoveryengine_v1beta.types import serving_config_service @@ -877,7 +877,7 @@ def sample_get_serving_config(): name (str): Required. The resource name of the ServingConfig to get. Format: - ``projects/{project_number}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -988,7 +988,7 @@ def sample_list_serving_configs(): parent (str): Required. Full resource name of the parent resource. Format: - ``projects/{project_number}/locations/{location}/collections/{collection}/engines/{engine}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/async_client.py index c9e8a9eecaae..ba7025c7e13d 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/async_client.py @@ -76,6 +76,8 @@ class SiteSearchEngineServiceAsyncClient: ) _DEFAULT_UNIVERSE = SiteSearchEngineServiceClient._DEFAULT_UNIVERSE + sitemap_path = staticmethod(SiteSearchEngineServiceClient.sitemap_path) + parse_sitemap_path = staticmethod(SiteSearchEngineServiceClient.parse_sitemap_path) site_search_engine_path = staticmethod( SiteSearchEngineServiceClient.site_search_engine_path ) @@ -1191,6 +1193,404 @@ async def sample_list_target_sites(): # Done; return the response. return response + async def create_sitemap( + self, + request: Optional[ + Union[site_search_engine_service.CreateSitemapRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sitemap: Optional[site_search_engine.Sitemap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + .. 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 discoveryengine_v1beta + + async def sample_create_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + sitemap = discoveryengine_v1beta.Sitemap() + sitemap.uri = "uri_value" + + request = discoveryengine_v1beta.CreateSitemapRequest( + parent="parent_value", + sitemap=sitemap, + ) + + # Make the request + operation = client.create_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateSitemapRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + method. + parent (:class:`str`): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sitemap (:class:`google.cloud.discoveryengine_v1beta.types.Sitemap`): + Required. The + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + to create. + + This corresponds to the ``sitemap`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.Sitemap` + A sitemap for the SiteSearchEngine. + + """ + # 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. + has_flattened_params = any([parent, sitemap]) + 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, site_search_engine_service.CreateSitemapRequest): + request = site_search_engine_service.CreateSitemapRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sitemap is not None: + request.sitemap = sitemap + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sitemap + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine.Sitemap, + metadata_type=site_search_engine_service.CreateSitemapMetadata, + ) + + # Done; return the response. + return response + + async def delete_sitemap( + self, + request: Optional[ + Union[site_search_engine_service.DeleteSitemapRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + .. 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 discoveryengine_v1beta + + async def sample_delete_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSitemapRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteSitemapRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + method. + name (:class:`str`): + Required. Full resource name of + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}``. + + If the caller does not have permission to access the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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. + has_flattened_params = any([name]) + 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, site_search_engine_service.DeleteSitemapRequest): + request = site_search_engine_service.DeleteSitemapRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_sitemap + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=site_search_engine_service.DeleteSitemapMetadata, + ) + + # Done; return the response. + return response + + async def fetch_sitemaps( + self, + request: Optional[ + Union[site_search_engine_service.FetchSitemapsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> site_search_engine_service.FetchSitemapsResponse: + r"""Fetch [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + a [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + .. 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 discoveryengine_v1beta + + async def sample_fetch_sitemaps(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.FetchSitemapsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.fetch_sitemaps(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + parent (:class:`str`): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.FetchSitemapsResponse: + Response message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + """ + # 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. + has_flattened_params = any([parent]) + 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, site_search_engine_service.FetchSitemapsRequest): + request = site_search_engine_service.FetchSitemapsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_sitemaps + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def enable_advanced_site_search( self, request: Optional[ diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/client.py index ce3759bfd48a..a6d264a4a185 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/client.py @@ -195,6 +195,30 @@ def transport(self) -> SiteSearchEngineServiceTransport: """ return self._transport + @staticmethod + def sitemap_path( + project: str, + location: str, + data_store: str, + sitemap: str, + ) -> str: + """Returns a fully-qualified sitemap string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}".format( + project=project, + location=location, + data_store=data_store, + sitemap=sitemap, + ) + + @staticmethod + def parse_sitemap_path(path: str) -> Dict[str, str]: + """Parses a sitemap path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/siteSearchEngine/sitemaps/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def site_search_engine_path( project: str, @@ -1611,6 +1635,395 @@ def sample_list_target_sites(): # Done; return the response. return response + def create_sitemap( + self, + request: Optional[ + Union[site_search_engine_service.CreateSitemapRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + sitemap: Optional[site_search_engine.Sitemap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + .. 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 discoveryengine_v1beta + + def sample_create_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + sitemap = discoveryengine_v1beta.Sitemap() + sitemap.uri = "uri_value" + + request = discoveryengine_v1beta.CreateSitemapRequest( + parent="parent_value", + sitemap=sitemap, + ) + + # Make the request + operation = client.create_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateSitemapRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + method. + parent (str): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sitemap (google.cloud.discoveryengine_v1beta.types.Sitemap): + Required. The + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + to create. + + This corresponds to the ``sitemap`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.Sitemap` + A sitemap for the SiteSearchEngine. + + """ + # 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. + has_flattened_params = any([parent, sitemap]) + 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, site_search_engine_service.CreateSitemapRequest): + request = site_search_engine_service.CreateSitemapRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sitemap is not None: + request.sitemap = sitemap + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sitemap] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine.Sitemap, + metadata_type=site_search_engine_service.CreateSitemapMetadata, + ) + + # Done; return the response. + return response + + def delete_sitemap( + self, + request: Optional[ + Union[site_search_engine_service.DeleteSitemapRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + .. 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 discoveryengine_v1beta + + def sample_delete_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSitemapRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteSitemapRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + method. + name (str): + Required. Full resource name of + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}``. + + If the caller does not have permission to access the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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. + has_flattened_params = any([name]) + 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, site_search_engine_service.DeleteSitemapRequest): + request = site_search_engine_service.DeleteSitemapRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_sitemap] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=site_search_engine_service.DeleteSitemapMetadata, + ) + + # Done; return the response. + return response + + def fetch_sitemaps( + self, + request: Optional[ + Union[site_search_engine_service.FetchSitemapsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> site_search_engine_service.FetchSitemapsResponse: + r"""Fetch [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + a [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + .. 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 discoveryengine_v1beta + + def sample_fetch_sitemaps(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.FetchSitemapsRequest( + parent="parent_value", + ) + + # Make the request + response = client.fetch_sitemaps(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + parent (str): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.FetchSitemapsResponse: + Response message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + """ + # 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. + has_flattened_params = any([parent]) + 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, site_search_engine_service.FetchSitemapsRequest): + request = site_search_engine_service.FetchSitemapsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_sitemaps] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def enable_advanced_site_search( self, request: Optional[ diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/base.py index 2f2ac63dc19a..b1b4e77c7b5f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/base.py @@ -168,6 +168,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_sitemap: gapic_v1.method.wrap_method( + self.create_sitemap, + default_timeout=None, + client_info=client_info, + ), + self.delete_sitemap: gapic_v1.method.wrap_method( + self.delete_sitemap, + default_timeout=None, + client_info=client_info, + ), + self.fetch_sitemaps: gapic_v1.method.wrap_method( + self.fetch_sitemaps, + default_timeout=None, + client_info=client_info, + ), self.enable_advanced_site_search: gapic_v1.method.wrap_method( self.enable_advanced_site_search, default_timeout=None, @@ -293,6 +308,36 @@ def list_target_sites( ]: raise NotImplementedError() + @property + def create_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.CreateSitemapRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.DeleteSitemapRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def fetch_sitemaps( + self, + ) -> Callable[ + [site_search_engine_service.FetchSitemapsRequest], + Union[ + site_search_engine_service.FetchSitemapsResponse, + Awaitable[site_search_engine_service.FetchSitemapsResponse], + ], + ]: + raise NotImplementedError() + @property def enable_advanced_site_search( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc.py index 3226263e0150..c3416b0b3396 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc.py @@ -461,6 +461,94 @@ def list_target_sites( ) return self._stubs["list_target_sites"] + @property + def create_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.CreateSitemapRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create sitemap method over gRPC. + + Creates a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + Returns: + Callable[[~.CreateSitemapRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_sitemap" not in self._stubs: + self._stubs["create_sitemap"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/CreateSitemap", + request_serializer=site_search_engine_service.CreateSitemapRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_sitemap"] + + @property + def delete_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.DeleteSitemapRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete sitemap method over gRPC. + + Deletes a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + Returns: + Callable[[~.DeleteSitemapRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sitemap" not in self._stubs: + self._stubs["delete_sitemap"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/DeleteSitemap", + request_serializer=site_search_engine_service.DeleteSitemapRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_sitemap"] + + @property + def fetch_sitemaps( + self, + ) -> Callable[ + [site_search_engine_service.FetchSitemapsRequest], + site_search_engine_service.FetchSitemapsResponse, + ]: + r"""Return a callable for the fetch sitemaps method over gRPC. + + Fetch [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + a [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Returns: + Callable[[~.FetchSitemapsRequest], + ~.FetchSitemapsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_sitemaps" not in self._stubs: + self._stubs["fetch_sitemaps"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/FetchSitemaps", + request_serializer=site_search_engine_service.FetchSitemapsRequest.serialize, + response_deserializer=site_search_engine_service.FetchSitemapsResponse.deserialize, + ) + return self._stubs["fetch_sitemaps"] + @property def enable_advanced_site_search( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc_asyncio.py index 1c5ec658ecd9..c95f3b68353f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/grpc_asyncio.py @@ -475,6 +475,96 @@ def list_target_sites( ) return self._stubs["list_target_sites"] + @property + def create_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.CreateSitemapRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create sitemap method over gRPC. + + Creates a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + Returns: + Callable[[~.CreateSitemapRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_sitemap" not in self._stubs: + self._stubs["create_sitemap"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/CreateSitemap", + request_serializer=site_search_engine_service.CreateSitemapRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_sitemap"] + + @property + def delete_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.DeleteSitemapRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete sitemap method over gRPC. + + Deletes a + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + + Returns: + Callable[[~.DeleteSitemapRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sitemap" not in self._stubs: + self._stubs["delete_sitemap"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/DeleteSitemap", + request_serializer=site_search_engine_service.DeleteSitemapRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_sitemap"] + + @property + def fetch_sitemaps( + self, + ) -> Callable[ + [site_search_engine_service.FetchSitemapsRequest], + Awaitable[site_search_engine_service.FetchSitemapsResponse], + ]: + r"""Return a callable for the fetch sitemaps method over gRPC. + + Fetch [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + a [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Returns: + Callable[[~.FetchSitemapsRequest], + Awaitable[~.FetchSitemapsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_sitemaps" not in self._stubs: + self._stubs["fetch_sitemaps"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1beta.SiteSearchEngineService/FetchSitemaps", + request_serializer=site_search_engine_service.FetchSitemapsRequest.serialize, + response_deserializer=site_search_engine_service.FetchSitemapsResponse.deserialize, + ) + return self._stubs["fetch_sitemaps"] + @property def enable_advanced_site_search( self, @@ -667,6 +757,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_sitemap: self._wrap_method( + self.create_sitemap, + default_timeout=None, + client_info=client_info, + ), + self.delete_sitemap: self._wrap_method( + self.delete_sitemap, + default_timeout=None, + client_info=client_info, + ), + self.fetch_sitemaps: self._wrap_method( + self.fetch_sitemaps, + default_timeout=None, + client_info=client_info, + ), self.enable_advanced_site_search: self._wrap_method( self.enable_advanced_site_search, default_timeout=None, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py index 18465042b88e..cef376fda99d 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest.py @@ -81,6 +81,14 @@ def post_batch_verify_target_sites(self, response): logging.log(f"Received response: {response}") return response + def pre_create_sitemap(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sitemap(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_target_site(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -89,6 +97,14 @@ def post_create_target_site(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_sitemap(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_sitemap(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_target_site(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -121,6 +137,14 @@ def post_fetch_domain_verification_status(self, response): logging.log(f"Received response: {response}") return response + def pre_fetch_sitemaps(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_sitemaps(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_site_search_engine(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -219,6 +243,31 @@ def post_batch_verify_target_sites( """ return response + def pre_create_sitemap( + self, + request: site_search_engine_service.CreateSitemapRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + site_search_engine_service.CreateSitemapRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_sitemap + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_create_sitemap( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_sitemap + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + def pre_create_target_site( self, request: site_search_engine_service.CreateTargetSiteRequest, @@ -244,6 +293,31 @@ def post_create_target_site( """ return response + def pre_delete_sitemap( + self, + request: site_search_engine_service.DeleteSitemapRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + site_search_engine_service.DeleteSitemapRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_sitemap + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_delete_sitemap( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_sitemap + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + def pre_delete_target_site( self, request: site_search_engine_service.DeleteTargetSiteRequest, @@ -347,6 +421,31 @@ def post_fetch_domain_verification_status( """ return response + def pre_fetch_sitemaps( + self, + request: site_search_engine_service.FetchSitemapsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + site_search_engine_service.FetchSitemapsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for fetch_sitemaps + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_fetch_sitemaps( + self, response: site_search_engine_service.FetchSitemapsResponse + ) -> site_search_engine_service.FetchSitemapsResponse: + """Post-rpc interceptor for fetch_sitemaps + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + def pre_get_site_search_engine( self, request: site_search_engine_service.GetSiteSearchEngineRequest, @@ -991,6 +1090,106 @@ def __call__( resp = self._interceptor.post_batch_verify_target_sites(resp) return resp + class _CreateSitemap( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.CreateSitemap") + + @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: site_search_engine_service.CreateSitemapRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create sitemap method over HTTP. + + Args: + request (~.site_search_engine_service.CreateSitemapRequest): + The request object. Request message for + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_http_options() + ) + request, metadata = self._interceptor.pre_create_sitemap(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_transcoded_request( + http_options, request + ) + + body = _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_query_params_json( + transcoded_request + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._CreateSitemap._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_sitemap(resp) + return resp + class _CreateTargetSite( _BaseSiteSearchEngineServiceRestTransport._BaseCreateTargetSite, SiteSearchEngineServiceRestStub, @@ -1093,6 +1292,100 @@ def __call__( resp = self._interceptor.post_create_target_site(resp) return resp + class _DeleteSitemap( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.DeleteSitemap") + + @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: site_search_engine_service.DeleteSitemapRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete sitemap method over HTTP. + + Args: + request (~.site_search_engine_service.DeleteSitemapRequest): + The request object. Request message for + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_sitemap(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap._get_query_params_json( + transcoded_request + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._DeleteSitemap._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_sitemap(resp) + return resp + class _DeleteTargetSite( _BaseSiteSearchEngineServiceRestTransport._BaseDeleteTargetSite, SiteSearchEngineServiceRestStub, @@ -1496,6 +1789,102 @@ def __call__( resp = self._interceptor.post_fetch_domain_verification_status(resp) return resp + class _FetchSitemaps( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps, + SiteSearchEngineServiceRestStub, + ): + def __hash__(self): + return hash("SiteSearchEngineServiceRestTransport.FetchSitemaps") + + @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: site_search_engine_service.FetchSitemapsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> site_search_engine_service.FetchSitemapsResponse: + r"""Call the fetch sitemaps method over HTTP. + + Args: + request (~.site_search_engine_service.FetchSitemapsRequest): + The request object. Request message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.site_search_engine_service.FetchSitemapsResponse: + Response message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + """ + + http_options = ( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps._get_http_options() + ) + request, metadata = self._interceptor.pre_fetch_sitemaps(request, metadata) + transcoded_request = _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps._get_query_params_json( + transcoded_request + ) + + # Send the request + response = ( + SiteSearchEngineServiceRestTransport._FetchSitemaps._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 = site_search_engine_service.FetchSitemapsResponse() + pb_resp = site_search_engine_service.FetchSitemapsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_sitemaps(resp) + return resp + class _GetSiteSearchEngine( _BaseSiteSearchEngineServiceRestTransport._BaseGetSiteSearchEngine, SiteSearchEngineServiceRestStub, @@ -2010,6 +2399,16 @@ def batch_verify_target_sites( # In C++ this would require a dynamic_cast return self._BatchVerifyTargetSites(self._session, self._host, self._interceptor) # type: ignore + @property + def create_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.CreateSitemapRequest], operations_pb2.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._CreateSitemap(self._session, self._host, self._interceptor) # type: ignore + @property def create_target_site( self, @@ -2020,6 +2419,16 @@ def create_target_site( # In C++ this would require a dynamic_cast return self._CreateTargetSite(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_sitemap( + self, + ) -> Callable[ + [site_search_engine_service.DeleteSitemapRequest], operations_pb2.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._DeleteSitemap(self._session, self._host, self._interceptor) # type: ignore + @property def delete_target_site( self, @@ -2063,6 +2472,17 @@ def fetch_domain_verification_status( # In C++ this would require a dynamic_cast return self._FetchDomainVerificationStatus(self._session, self._host, self._interceptor) # type: ignore + @property + def fetch_sitemaps( + self, + ) -> Callable[ + [site_search_engine_service.FetchSitemapsRequest], + site_search_engine_service.FetchSitemapsResponse, + ]: + # 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._FetchSitemaps(self._session, self._host, self._interceptor) # type: ignore + @property def get_site_search_engine( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest_base.py index 0f74c2c703eb..c5d21da723f3 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest_base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/services/site_search_engine_service/transports/rest_base.py @@ -215,6 +215,68 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCreateSitemap: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/sitemaps", + "body": "sitemap", + }, + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/sitemaps", + "body": "sitemap", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.CreateSitemapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseCreateSitemap._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCreateTargetSite: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -277,6 +339,57 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseDeleteSitemap: + 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": "/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/sitemaps/*}", + }, + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/sitemaps/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.DeleteSitemapRequest.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=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseDeleteSitemap._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseDeleteTargetSite: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -507,6 +620,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseFetchSitemaps: + 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": "/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/sitemaps:fetch", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = site_search_engine_service.FetchSitemapsRequest.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=True, + ) + ) + query_params.update( + _BaseSiteSearchEngineServiceRestTransport._BaseFetchSitemaps._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetSiteSearchEngine: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/__init__.py index cc7c07b55354..a5cda2b60529 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/__init__.py @@ -28,7 +28,12 @@ UserInfo, ) from .completion import CompletionSuggestion, SuggestionDenyListEntry -from .completion_service import CompleteQueryRequest, CompleteQueryResponse +from .completion_service import ( + AdvancedCompleteQueryRequest, + AdvancedCompleteQueryResponse, + CompleteQueryRequest, + CompleteQueryResponse, +) from .control import Condition, Control from .control_service import ( CreateControlRequest, @@ -65,7 +70,12 @@ UpdateSessionRequest, ) from .custom_tuning_model import CustomTuningModel -from .data_store import DataStore, LanguageInfo +from .data_store import ( + DataStore, + LanguageInfo, + NaturalLanguageQueryUnderstandingConfig, + WorkspaceConfig, +) from .data_store_service import ( CreateDataStoreMetadata, CreateDataStoreRequest, @@ -118,8 +128,11 @@ CheckGroundingRequest, CheckGroundingResponse, CheckGroundingSpec, + GenerateGroundedContentRequest, + GenerateGroundedContentResponse, + GroundedGenerationContent, ) -from .grounding import FactChunk, GroundingFact +from .grounding import FactChunk, GroundingConfig, GroundingFact from .import_config import ( AlloyDbSource, BigQuerySource, @@ -212,7 +225,12 @@ UpdateServingConfigRequest, ) from .session import Query, Session -from .site_search_engine import SiteSearchEngine, SiteVerificationInfo, TargetSite +from .site_search_engine import ( + Sitemap, + SiteSearchEngine, + SiteVerificationInfo, + TargetSite, +) from .site_search_engine_service import ( BatchCreateTargetSiteMetadata, BatchCreateTargetSitesRequest, @@ -220,8 +238,12 @@ BatchVerifyTargetSitesMetadata, BatchVerifyTargetSitesRequest, BatchVerifyTargetSitesResponse, + CreateSitemapMetadata, + CreateSitemapRequest, CreateTargetSiteMetadata, CreateTargetSiteRequest, + DeleteSitemapMetadata, + DeleteSitemapRequest, DeleteTargetSiteMetadata, DeleteTargetSiteRequest, DisableAdvancedSiteSearchMetadata, @@ -232,6 +254,8 @@ EnableAdvancedSiteSearchResponse, FetchDomainVerificationStatusRequest, FetchDomainVerificationStatusResponse, + FetchSitemapsRequest, + FetchSitemapsResponse, GetSiteSearchEngineRequest, GetTargetSiteRequest, ListTargetSitesRequest, @@ -269,6 +293,8 @@ "SolutionType", "CompletionSuggestion", "SuggestionDenyListEntry", + "AdvancedCompleteQueryRequest", + "AdvancedCompleteQueryResponse", "CompleteQueryRequest", "CompleteQueryResponse", "Condition", @@ -304,6 +330,8 @@ "CustomTuningModel", "DataStore", "LanguageInfo", + "NaturalLanguageQueryUnderstandingConfig", + "WorkspaceConfig", "CreateDataStoreMetadata", "CreateDataStoreRequest", "DeleteDataStoreMetadata", @@ -348,7 +376,11 @@ "CheckGroundingRequest", "CheckGroundingResponse", "CheckGroundingSpec", + "GenerateGroundedContentRequest", + "GenerateGroundedContentResponse", + "GroundedGenerationContent", "FactChunk", + "GroundingConfig", "GroundingFact", "AlloyDbSource", "BigQuerySource", @@ -434,6 +466,7 @@ "UpdateServingConfigRequest", "Query", "Session", + "Sitemap", "SiteSearchEngine", "SiteVerificationInfo", "TargetSite", @@ -443,8 +476,12 @@ "BatchVerifyTargetSitesMetadata", "BatchVerifyTargetSitesRequest", "BatchVerifyTargetSitesResponse", + "CreateSitemapMetadata", + "CreateSitemapRequest", "CreateTargetSiteMetadata", "CreateTargetSiteRequest", + "DeleteSitemapMetadata", + "DeleteSitemapRequest", "DeleteTargetSiteMetadata", "DeleteTargetSiteRequest", "DisableAdvancedSiteSearchMetadata", @@ -455,6 +492,8 @@ "EnableAdvancedSiteSearchResponse", "FetchDomainVerificationStatusRequest", "FetchDomainVerificationStatusResponse", + "FetchSitemapsRequest", + "FetchSitemapsResponse", "GetSiteSearchEngineRequest", "GetTargetSiteRequest", "ListTargetSitesRequest", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/answer.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/answer.py index 1347bf5c6e59..6d2fd7ba7b02 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/answer.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/answer.py @@ -88,7 +88,10 @@ class AnswerSkippedReason(proto.Enum): ADVERSARIAL_QUERY_IGNORED (1): The adversarial query ignored case. NON_ANSWER_SEEKING_QUERY_IGNORED (2): - The non-answer seeking query ignored case. + The non-answer seeking query ignored case + + Google skips the answer if the query is chit + chat. OUT_OF_DOMAIN_QUERY_IGNORED (3): The out-of-domain query ignored case. @@ -117,6 +120,16 @@ class AnswerSkippedReason(proto.Enum): Google skips the summary if there is a customer policy violation detected. The policy is defined by the customer. + NON_ANSWER_SEEKING_QUERY_IGNORED_V2 (8): + The non-answer seeking query ignored case. + + Google skips the answer if the query doesn't + have clear intent. + LOW_GROUNDED_ANSWER (9): + The low-grounded answer case. + + Google skips the answer if a well grounded + answer was unable to be generated. """ ANSWER_SKIPPED_REASON_UNSPECIFIED = 0 ADVERSARIAL_QUERY_IGNORED = 1 @@ -126,6 +139,8 @@ class AnswerSkippedReason(proto.Enum): NO_RELEVANT_CONTENT = 5 JAIL_BREAKING_QUERY_IGNORED = 6 CUSTOMER_POLICY_VIOLATION = 7 + NON_ANSWER_SEEKING_QUERY_IGNORED_V2 = 8 + LOW_GROUNDED_ANSWER = 9 class Citation(proto.Message): r"""Citation info for a segment. @@ -487,9 +502,7 @@ class SearchResult(proto.Message): Data representation. The structured JSON data for the document. It's populated from the struct data from the - Document , or the Chunk in - search result - . + Document, or the Chunk in search result. """ class SnippetInfo(proto.Message): @@ -645,14 +658,19 @@ class Type(proto.Enum): ADVERSARIAL_QUERY (1): Adversarial query classification type. NON_ANSWER_SEEKING_QUERY (2): - Non-answer-seeking query classification type. + Non-answer-seeking query classification type, + for chit chat. JAIL_BREAKING_QUERY (3): Jail-breaking query classification type. + NON_ANSWER_SEEKING_QUERY_V2 (4): + Non-answer-seeking query classification type, + for no clear intent. """ TYPE_UNSPECIFIED = 0 ADVERSARIAL_QUERY = 1 NON_ANSWER_SEEKING_QUERY = 2 JAIL_BREAKING_QUERY = 3 + NON_ANSWER_SEEKING_QUERY_V2 = 4 type_: "Answer.QueryUnderstandingInfo.QueryClassificationInfo.Type" = ( proto.Field( diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/completion_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/completion_service.py index 8964bc714780..adeddd021dbe 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/completion_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/completion_service.py @@ -17,13 +17,19 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import document as gcd_document + __protobuf__ = proto.module( package="google.cloud.discoveryengine.v1beta", manifest={ "CompleteQueryRequest", "CompleteQueryResponse", + "AdvancedCompleteQueryRequest", + "AdvancedCompleteQueryResponse", }, ) @@ -166,4 +172,430 @@ class QuerySuggestion(proto.Message): ) +class AdvancedCompleteQueryRequest(proto.Message): + r"""Request message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. . + + Attributes: + completion_config (str): + Required. The completion_config of the parent dataStore or + engine resource name for which the completion is performed, + such as + ``projects/*/locations/global/collections/default_collection/dataStores/*/completionConfig`` + ``projects/*/locations/global/collections/default_collection/engines/*/completionConfig``. + query (str): + Required. The typeahead input used to fetch suggestions. + Maximum length is 128 characters. + + The query can not be empty for most of the suggestion types. + If it is empty, an ``INVALID_ARGUMENT`` error is returned. + The exception is when the suggestion_types contains only the + type ``RECENT_SEARCH``, the query can be an empty string. + The is called "zero prefix" feature, which returns user's + recently searched queries given the empty query. + query_model (str): + Specifies the autocomplete data model. This overrides any + model specified in the Configuration > Autocomplete section + of the Cloud console. Currently supported values: + + - ``document`` - Using suggestions generated from + user-imported documents. + - ``search-history`` - Using suggestions generated from the + past history of + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API calls. Do not use it when there is no traffic for + Search API. + - ``user-event`` - Using suggestions generated from + user-imported search events. + - ``document-completable`` - Using suggestions taken + directly from user-imported document fields marked as + completable. + + Default values: + + - ``document`` is the default model for regular dataStores. + - ``search-history`` is the default model for site search + dataStores. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + and + [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.SearchRequest.user_pseudo_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 + user_info (google.cloud.discoveryengine_v1beta.types.UserInfo): + Optional. Information about the end user. + + This should be the same identifier information as + [UserEvent.user_info][google.cloud.discoveryengine.v1beta.UserEvent.user_info] + and + [SearchRequest.user_info][google.cloud.discoveryengine.v1beta.SearchRequest.user_info]. + include_tail_suggestions (bool): + Indicates if tail suggestions should be + returned if there are no suggestions that match + the full query. Even if set to true, if there + are suggestions that match the full query, those + are returned and no tail suggestions are + returned. + boost_spec (google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest.BoostSpec): + Optional. Specification to boost suggestions + matching the condition. + suggestion_types (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest.SuggestionType]): + Optional. Suggestion types to return. If + empty or unspecified, query suggestions are + returned. Only one suggestion type is supported + at the moment. + """ + + class SuggestionType(proto.Enum): + r"""Suggestion type to return. + + Values: + SUGGESTION_TYPE_UNSPECIFIED (0): + Default value. + QUERY (1): + Returns query suggestions. + PEOPLE (2): + Returns people suggestions. + CONTENT (3): + Returns content suggestions. + RECENT_SEARCH (4): + Returns recent search suggestions. + GOOGLE_WORKSPACE (5): + Returns Google Workspace suggestions. + """ + SUGGESTION_TYPE_UNSPECIFIED = 0 + QUERY = 1 + PEOPLE = 2 + CONTENT = 3 + RECENT_SEARCH = 4 + GOOGLE_WORKSPACE = 5 + + class BoostSpec(proto.Message): + r"""Specification to boost suggestions based on the condtion of + the suggestion. + + Attributes: + condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a + suggestion matches multiple conditions in the + specifictions, boost values from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + + Note: Currently only support language condition + boost. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to suggestions which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + is the same as `filter expression + syntax `__. + Currently, the only supported condition is a list of BCP-47 + lang codes. + + Example: + + - To boost suggestions in languages ``en`` or ``fr``: + ``(lang_code: ANY("en", "fr"))`` + boost (float): + Strength of the boost, which should be in [-1, 1]. Negative + boost means demotion. Default is 0.0. + + Setting to 1.0 gives the suggestions a big promotion. + However, it does not necessarily mean that the top result + will be a boosted suggestion. + + Setting to -1.0 gives the suggestions a big demotion. + However, other suggestions that are relevant might still be + shown. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition: str = proto.Field( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs: MutableSequence[ + "AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec", + ) + + completion_config: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + query_model: str = proto.Field( + proto.STRING, + number=3, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=4, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=9, + message=common.UserInfo, + ) + include_tail_suggestions: bool = proto.Field( + proto.BOOL, + number=5, + ) + boost_spec: BoostSpec = proto.Field( + proto.MESSAGE, + number=6, + message=BoostSpec, + ) + suggestion_types: MutableSequence[SuggestionType] = proto.RepeatedField( + proto.ENUM, + number=7, + enum=SuggestionType, + ) + + +class AdvancedCompleteQueryResponse(proto.Message): + r"""Response message for + [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery] + method. + + Attributes: + query_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.QuerySuggestion]): + Results of the matched query suggestions. The + result list is ordered and the first result is a + top suggestion. + tail_match_triggered (bool): + True if the returned suggestions are all tail suggestions. + + For tail matching to be triggered, include_tail_suggestions + in the request must be true and there must be no suggestions + that match the full query. + people_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.PersonSuggestion]): + Results of the matched people suggestions. + The result list is ordered and the first result + is the top suggestion. + content_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.ContentSuggestion]): + Results of the matched content suggestions. + The result list is ordered and the first result + is the top suggestion. + recent_search_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.RecentSearchSuggestion]): + Results of the matched "recent search" + suggestions. The result list is ordered and the + first result is the top suggestion. + """ + + class QuerySuggestion(proto.Message): + r"""Suggestions as search queries. + + Attributes: + suggestion (str): + The suggestion for the query. + completable_field_paths (MutableSequence[str]): + The unique document field paths that serve as + the source of this suggestion if it was + generated from completable fields. + + This field is only populated for the + document-completable model. + data_store (MutableSequence[str]): + The name of the dataStore that this + suggestion belongs to. + """ + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + completable_field_paths: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + data_store: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class PersonSuggestion(proto.Message): + r"""Suggestions as people. + + Attributes: + suggestion (str): + The suggestion for the query. + person_type (google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.PersonSuggestion.PersonType): + The type of the person. + document (google.cloud.discoveryengine_v1beta.types.Document): + The document data snippet in the suggestion. + Only a subset of fields is populated. + data_store (str): + The name of the dataStore that this + suggestion belongs to. + """ + + class PersonType(proto.Enum): + r"""The type of the person based on the source. + + Values: + PERSON_TYPE_UNSPECIFIED (0): + Default value. + CLOUD_IDENTITY (1): + The suggestion is from a GOOGLE_IDENTITY source. + THIRD_PARTY_IDENTITY (2): + The suggestion is from a THIRD_PARTY_IDENTITY source. + """ + PERSON_TYPE_UNSPECIFIED = 0 + CLOUD_IDENTITY = 1 + THIRD_PARTY_IDENTITY = 2 + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + person_type: "AdvancedCompleteQueryResponse.PersonSuggestion.PersonType" = ( + proto.Field( + proto.ENUM, + number=2, + enum="AdvancedCompleteQueryResponse.PersonSuggestion.PersonType", + ) + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_document.Document, + ) + data_store: str = proto.Field( + proto.STRING, + number=5, + ) + + class ContentSuggestion(proto.Message): + r"""Suggestions as content. + + Attributes: + suggestion (str): + The suggestion for the query. + content_type (google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse.ContentSuggestion.ContentType): + The type of the content suggestion. + document (google.cloud.discoveryengine_v1beta.types.Document): + The document data snippet in the suggestion. + Only a subset of fields will be populated. + data_store (str): + The name of the dataStore that this + suggestion belongs to. + """ + + class ContentType(proto.Enum): + r"""The type of the content returned for content suggestions. + + Values: + CONTENT_TYPE_UNSPECIFIED (0): + Default value. + GOOGLE_WORKSPACE (1): + The suggestion is from a Google Workspace + source. + THIRD_PARTY (2): + The suggestion is from a third party source. + """ + CONTENT_TYPE_UNSPECIFIED = 0 + GOOGLE_WORKSPACE = 1 + THIRD_PARTY = 2 + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + content_type: "AdvancedCompleteQueryResponse.ContentSuggestion.ContentType" = ( + proto.Field( + proto.ENUM, + number=2, + enum="AdvancedCompleteQueryResponse.ContentSuggestion.ContentType", + ) + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=4, + message=gcd_document.Document, + ) + data_store: str = proto.Field( + proto.STRING, + number=5, + ) + + class RecentSearchSuggestion(proto.Message): + r"""Suggestions from recent search history. + + Attributes: + suggestion (str): + The suggestion for the query. + recent_search_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this recent rearch happened. + """ + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + recent_search_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QuerySuggestion, + ) + tail_match_triggered: bool = proto.Field( + proto.BOOL, + number=2, + ) + people_suggestions: MutableSequence[PersonSuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=PersonSuggestion, + ) + content_suggestions: MutableSequence[ContentSuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=ContentSuggestion, + ) + recent_search_suggestions: MutableSequence[ + RecentSearchSuggestion + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=RecentSearchSuggestion, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/control.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/control.py index f4a052314afd..a179fda7f085 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/control.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/control.py @@ -37,14 +37,21 @@ class Condition(proto.Message): Attributes: query_terms (MutableSequence[google.cloud.discoveryengine_v1beta.types.Condition.QueryTerm]): - Search only - A list of terms to match the query on. + Search only A list of terms to match the query on. Cannot be + set when + [Condition.query_regex][google.cloud.discoveryengine.v1beta.Condition.query_regex] + is set. Maximum of 10 query terms. active_time_range (MutableSequence[google.cloud.discoveryengine_v1beta.types.Condition.TimeRange]): Range of time(s) specifying when condition is active. Maximum of 10 time ranges. + query_regex (str): + Optional. Query regex to match the whole search query. + Cannot be set when + [Condition.query_terms][google.cloud.discoveryengine.v1beta.Condition.query_terms] + is set. This is currently supporting promotion use case. """ class QueryTerm(proto.Message): @@ -107,6 +114,10 @@ class TimeRange(proto.Message): number=3, message=TimeRange, ) + query_regex: str = proto.Field( + proto.STRING, + number=4, + ) class Control(proto.Message): diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/control_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/control_service.py index a3b899dff539..918391068d3b 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/control_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/control_service.py @@ -41,9 +41,9 @@ class CreateControlRequest(proto.Message): Attributes: parent (str): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`` or - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}``. + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. control (google.cloud.discoveryengine_v1beta.types.Control): Required. The Control to create. control_id (str): @@ -105,7 +105,7 @@ class DeleteControlRequest(proto.Message): name (str): Required. The resource name of the Control to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` """ name: str = proto.Field( @@ -120,7 +120,7 @@ class GetControlRequest(proto.Message): Attributes: name (str): Required. The resource name of the Control to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/controls/{control_id}`` """ name: str = proto.Field( @@ -135,9 +135,9 @@ class ListControlsRequest(proto.Message): Attributes: parent (str): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`` or - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}``. + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. page_size (int): Optional. Maximum number of results to return. If unspecified, defaults to 50. Max diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py index e09b08bc0e50..05654d08d35c 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py @@ -58,16 +58,16 @@ class ConverseConversationRequest(proto.Message): name (str): Required. The resource name of the Conversation to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` to activate auto session mode, which automatically creates a new conversation inside a ConverseConversation session. query (google.cloud.discoveryengine_v1beta.types.TextInput): Required. Current user input. serving_config (str): The resource name of the Serving Config to use. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` If this is not set, the default serving config will be used. conversation (google.cloud.discoveryengine_v1beta.types.Conversation): The conversation to be used by auto session @@ -218,7 +218,7 @@ class CreateConversationRequest(proto.Message): Attributes: parent (str): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` conversation (google.cloud.discoveryengine_v1beta.types.Conversation): Required. The conversation to create. """ @@ -269,7 +269,7 @@ class DeleteConversationRequest(proto.Message): name (str): Required. The resource name of the Conversation to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` """ name: str = proto.Field( @@ -285,7 +285,7 @@ class GetConversationRequest(proto.Message): name (str): Required. The resource name of the Conversation to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` """ name: str = proto.Field( @@ -300,7 +300,7 @@ class ListConversationsRequest(proto.Message): Attributes: parent (str): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` page_size (int): Maximum number of results to return. If unspecified, defaults to 50. Max allowed value @@ -402,6 +402,8 @@ class AnswerQueryRequest(proto.Message): Model specification. related_questions_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.RelatedQuestionsSpec): Related questions specification. + grounding_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.GroundingSpec): + Optional. Grounding specification. answer_generation_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.AnswerGenerationSpec): Answer generation specification. search_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec): @@ -409,6 +411,9 @@ class AnswerQueryRequest(proto.Message): query_understanding_spec (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.QueryUnderstandingSpec): Query understanding specification. asynchronous_mode (bool): + Deprecated: This field is deprecated. Streaming Answer API + will be supported. + Asynchronous mode control. If enabled, the response will be returned with @@ -483,6 +488,50 @@ class RelatedQuestionsSpec(proto.Message): number=1, ) + class GroundingSpec(proto.Message): + r"""Grounding specification. + + Attributes: + include_grounding_supports (bool): + Optional. Specifies whether to include grounding_supports in + the answer. The default value is ``false``. + + When this field is set to ``true``, returned answer will + have ``grounding_score`` and will contain GroundingSupports + for each claim. + filtering_level (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.GroundingSpec.FilteringLevel): + Optional. Specifies whether to enable the + filtering based on grounding score and at what + level. + """ + + class FilteringLevel(proto.Enum): + r"""Level to filter based on answer grounding. + + Values: + FILTERING_LEVEL_UNSPECIFIED (0): + Default is no filter + FILTERING_LEVEL_LOW (1): + Filter answers based on a low threshold. + FILTERING_LEVEL_HIGH (2): + Filter answers based on a high threshold. + """ + FILTERING_LEVEL_UNSPECIFIED = 0 + FILTERING_LEVEL_LOW = 1 + FILTERING_LEVEL_HIGH = 2 + + include_grounding_supports: bool = proto.Field( + proto.BOOL, + number=2, + ) + filtering_level: "AnswerQueryRequest.GroundingSpec.FilteringLevel" = ( + proto.Field( + proto.ENUM, + number=3, + enum="AnswerQueryRequest.GroundingSpec.FilteringLevel", + ) + ) + class AnswerGenerationSpec(proto.Message): r"""Answer generation specification. @@ -532,6 +581,19 @@ class AnswerGenerationSpec(proto.Message): automatically by the service. This field is a member of `oneof`_ ``_ignore_low_relevant_content``. + ignore_jail_breaking_query (bool): + Optional. Specifies whether to filter out jail-breaking + queries. The default value is ``false``. + + Google employs search-query classification to detect + jail-breaking queries. No summary is returned if the search + query is classified as a jail-breaking query. A user might + add instructions to the query to change the tone, style, + language, content of the answer, or ask the model to act as + a different entity, e.g. "Reply in the tone of a competing + company's CEO". If this field is set to ``true``, we skip + generating summaries for jail-breaking queries and return + fallback messages instead. """ class ModelSpec(proto.Message): @@ -593,6 +655,10 @@ class PromptSpec(proto.Message): number=7, optional=True, ) + ignore_jail_breaking_query: bool = proto.Field( + proto.BOOL, + number=8, + ) class SearchSpec(proto.Message): r"""Search specification. @@ -669,6 +735,10 @@ class SearchParams(proto.Message): with multiple dataStores use case. For single dataStore within an engine, they should use the specs at the top level. + natural_language_query_understanding_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.NaturalLanguageQueryUnderstandingSpec): + Optional. Specification to enable natural + language understanding capabilities for search + requests. """ max_return_results: int = proto.Field( @@ -700,6 +770,11 @@ class SearchParams(proto.Message): number=7, message=search_service.SearchRequest.DataStoreSpec, ) + natural_language_query_understanding_spec: search_service.SearchRequest.NaturalLanguageQueryUnderstandingSpec = proto.Field( + proto.MESSAGE, + number=8, + message=search_service.SearchRequest.NaturalLanguageQueryUnderstandingSpec, + ) class SearchResultList(proto.Message): r"""Search result list. @@ -741,11 +816,16 @@ class UnstructuredDocumentInfo(proto.Message): title (str): Title. document_contexts (MutableSequence[google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.DocumentContext]): - List of document contexts. + List of document contexts. The content will + be used for Answer Generation. This is supposed + to be the main content of the document that can + be long and comprehensive. extractive_segments (MutableSequence[google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.ExtractiveSegment]): List of extractive segments. extractive_answers (MutableSequence[google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo.ExtractiveAnswer]): - List of extractive answers. + Deprecated: This field is deprecated and will have no effect + on the Answer generation. Please use document_contexts and + extractive_segments fields. List of extractive answers. """ class DocumentContext(proto.Message): @@ -755,7 +835,8 @@ class DocumentContext(proto.Message): page_identifier (str): Page identifier. content (str): - Document content. + Document content to be used for answer + generation. """ page_identifier: str = proto.Field( @@ -770,6 +851,8 @@ class DocumentContext(proto.Message): class ExtractiveSegment(proto.Message): r"""Extractive segment. `Guide `__ + Answer generation will only use it if document_contexts is empty. + This is supposed to be shorter snippets. Attributes: page_identifier (str): @@ -849,8 +932,31 @@ class ChunkInfo(proto.Message): Chunk resource name. content (str): Chunk textual content. + document_metadata (google.cloud.discoveryengine_v1beta.types.AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo.DocumentMetadata): + Metadata of the document from the current + chunk. """ + class DocumentMetadata(proto.Message): + r"""Document metadata contains the information of the document of + the current chunk. + + Attributes: + uri (str): + Uri of the document. + title (str): + Title of the document. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + chunk: str = proto.Field( proto.STRING, number=1, @@ -859,6 +965,11 @@ class ChunkInfo(proto.Message): proto.STRING, number=2, ) + document_metadata: "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo.DocumentMetadata" = proto.Field( + proto.MESSAGE, + number=4, + message="AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.ChunkInfo.DocumentMetadata", + ) unstructured_document_info: "AnswerQueryRequest.SearchSpec.SearchResultList.SearchResult.UnstructuredDocumentInfo" = proto.Field( proto.MESSAGE, @@ -923,14 +1034,19 @@ class Type(proto.Enum): ADVERSARIAL_QUERY (1): Adversarial query classification type. NON_ANSWER_SEEKING_QUERY (2): - Non-answer-seeking query classification type. + Non-answer-seeking query classification type, + for chit chat. JAIL_BREAKING_QUERY (3): Jail-breaking query classification type. + NON_ANSWER_SEEKING_QUERY_V2 (4): + Non-answer-seeking query classification type, + for no clear intent. """ TYPE_UNSPECIFIED = 0 ADVERSARIAL_QUERY = 1 NON_ANSWER_SEEKING_QUERY = 2 JAIL_BREAKING_QUERY = 3 + NON_ANSWER_SEEKING_QUERY_V2 = 4 types: MutableSequence[ "AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type" @@ -996,6 +1112,11 @@ class QueryRephraserSpec(proto.Message): number=5, message=RelatedQuestionsSpec, ) + grounding_spec: GroundingSpec = proto.Field( + proto.MESSAGE, + number=6, + message=GroundingSpec, + ) answer_generation_spec: AnswerGenerationSpec = proto.Field( proto.MESSAGE, number=7, @@ -1071,7 +1192,7 @@ class GetAnswerRequest(proto.Message): Attributes: name (str): Required. The resource name of the Answer to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/engines/{engine_id}/sessions/{session_id}/answers/{answer_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine_id}/sessions/{session_id}/answers/{answer_id}`` """ name: str = proto.Field( @@ -1086,7 +1207,7 @@ class CreateSessionRequest(proto.Message): Attributes: parent (str): Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` session (google.cloud.discoveryengine_v1beta.types.Session): Required. The session to create. """ @@ -1137,7 +1258,7 @@ class DeleteSessionRequest(proto.Message): name (str): Required. The resource name of the Session to delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` """ name: str = proto.Field( @@ -1152,7 +1273,7 @@ class GetSessionRequest(proto.Message): Attributes: name (str): Required. The resource name of the Session to get. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}/sessions/{session_id}`` """ name: str = proto.Field( @@ -1167,7 +1288,7 @@ class ListSessionsRequest(proto.Message): Attributes: parent (str): Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}`` page_size (int): Maximum number of results to return. If unspecified, defaults to 50. Max allowed value diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/custom_tuning_model.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/custom_tuning_model.py index d0f53427c220..914deed03260 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/custom_tuning_model.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/custom_tuning_model.py @@ -36,8 +36,9 @@ class CustomTuningModel(proto.Message): Required. The fully qualified resource name of the model. Format: - ``projects/{project_number}/locations/{location}/collections/{collection}/dataStores/{data_store}/customTuningModels/{custom_tuning_model}`` - model must be an alpha-numerical string with limit of 40 + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/customTuningModels/{custom_tuning_model}``. + + Model must be an alpha-numerical string with limit of 40 characters. display_name (str): The display name of the model. @@ -47,11 +48,15 @@ class CustomTuningModel(proto.Message): The state that the model is in (e.g.``TRAINING`` or ``TRAINING_FAILED``). create_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp the Model was created at. + Deprecated: Timestamp the Model was created + at. training_start_time (google.protobuf.timestamp_pb2.Timestamp): Timestamp the model training was initiated. metrics (MutableMapping[str, float]): The metrics of the trained model. + error_message (str): + Currently this is only populated if the model state is + ``INPUT_VALIDATION_FAILED``. """ class ModelState(proto.Enum): @@ -119,6 +124,10 @@ class ModelState(proto.Enum): proto.DOUBLE, number=7, ) + error_message: str = proto.Field( + proto.STRING, + number=8, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/data_store.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/data_store.py index 55de9ee663b9..77486f795e25 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/data_store.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/data_store.py @@ -31,6 +31,8 @@ manifest={ "DataStore", "LanguageInfo", + "NaturalLanguageQueryUnderstandingConfig", + "WorkspaceConfig", }, ) @@ -79,6 +81,18 @@ class DataStore(proto.Message): was created at. language_info (google.cloud.discoveryengine_v1beta.types.LanguageInfo): Language info for DataStore. + natural_language_query_understanding_config (google.cloud.discoveryengine_v1beta.types.NaturalLanguageQueryUnderstandingConfig): + Optional. Configuration for Natural Language + Query Understanding. + billing_estimation (google.cloud.discoveryengine_v1beta.types.DataStore.BillingEstimation): + Output only. Data size estimation for + billing. + workspace_config (google.cloud.discoveryengine_v1beta.types.WorkspaceConfig): + Config to store data store type configuration for workspace + data. This must be set when + [DataStore.content_config][google.cloud.discoveryengine.v1beta.DataStore.content_config] + is set as + [DataStore.ContentConfig.GOOGLE_WORKSPACE][google.cloud.discoveryengine.v1beta.DataStore.ContentConfig.GOOGLE_WORKSPACE]. document_processing_config (google.cloud.discoveryengine_v1beta.types.DocumentProcessingConfig): Configuration for Document understanding and enrichment. @@ -100,6 +114,9 @@ class DataStore(proto.Message): The provided schema will be validated against certain rules on schema. Learn more from `this doc `__. + serving_config_data_store (google.cloud.discoveryengine_v1beta.types.DataStore.ServingConfigDataStore): + Optional. Stores serving config at DataStore + level. """ class ContentConfig(proto.Enum): @@ -117,11 +134,79 @@ class ContentConfig(proto.Enum): PUBLIC_WEBSITE (3): The data store is used for public website search. + GOOGLE_WORKSPACE (4): + The data store is used for workspace search. Details of + workspace data store are specified in the + [WorkspaceConfig][google.cloud.discoveryengine.v1beta.WorkspaceConfig]. """ CONTENT_CONFIG_UNSPECIFIED = 0 NO_CONTENT = 1 CONTENT_REQUIRED = 2 PUBLIC_WEBSITE = 3 + GOOGLE_WORKSPACE = 4 + + class BillingEstimation(proto.Message): + r"""Estimation of data size per data store. + + Attributes: + structured_data_size (int): + Data size for structured data in terms of + bytes. + unstructured_data_size (int): + Data size for unstructured data in terms of + bytes. + website_data_size (int): + Data size for websites in terms of bytes. + structured_data_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last updated timestamp for structured data. + unstructured_data_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last updated timestamp for unstructured data. + website_data_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last updated timestamp for websites. + """ + + structured_data_size: int = proto.Field( + proto.INT64, + number=1, + ) + unstructured_data_size: int = proto.Field( + proto.INT64, + number=2, + ) + website_data_size: int = proto.Field( + proto.INT64, + number=3, + ) + structured_data_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + unstructured_data_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + website_data_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + class ServingConfigDataStore(proto.Message): + r"""Stores information regarding the serving configurations at + DataStore level. + + Attributes: + disabled_for_serving (bool): + If set true, the DataStore will not be + available for serving search requests. + """ + + disabled_for_serving: bool = proto.Field( + proto.BOOL, + number=1, + ) name: str = proto.Field( proto.STRING, @@ -160,6 +245,21 @@ class ContentConfig(proto.Enum): number=14, message="LanguageInfo", ) + natural_language_query_understanding_config: "NaturalLanguageQueryUnderstandingConfig" = proto.Field( + proto.MESSAGE, + number=34, + message="NaturalLanguageQueryUnderstandingConfig", + ) + billing_estimation: BillingEstimation = proto.Field( + proto.MESSAGE, + number=23, + message=BillingEstimation, + ) + workspace_config: "WorkspaceConfig" = proto.Field( + proto.MESSAGE, + number=25, + message="WorkspaceConfig", + ) document_processing_config: gcd_document_processing_config.DocumentProcessingConfig = proto.Field( proto.MESSAGE, number=27, @@ -170,6 +270,11 @@ class ContentConfig(proto.Enum): number=28, message=schema.Schema, ) + serving_config_data_store: ServingConfigDataStore = proto.Field( + proto.MESSAGE, + number=30, + message=ServingConfigDataStore, + ) class LanguageInfo(proto.Message): @@ -210,4 +315,114 @@ class LanguageInfo(proto.Message): ) +class NaturalLanguageQueryUnderstandingConfig(proto.Message): + r"""Configuration for Natural Language Query Understanding. + + Attributes: + mode (google.cloud.discoveryengine_v1beta.types.NaturalLanguageQueryUnderstandingConfig.Mode): + Mode of Natural Language Query Understanding. If this field + is unset, the behavior defaults to + [NaturalLanguageQueryUnderstandingConfig.Mode.DISABLED][google.cloud.discoveryengine.v1beta.NaturalLanguageQueryUnderstandingConfig.Mode.DISABLED]. + """ + + class Mode(proto.Enum): + r"""Mode of Natural Language Query Understanding. When the + NaturalLanguageQueryUnderstandingConfig.Mode is ENABLED, the + natural language understanding capabilities will be enabled for + a search request if the + NaturalLanguageQueryUnderstandingSpec.FilterExtractionCondition + in the SearchRequest is ENABLED. + + Values: + MODE_UNSPECIFIED (0): + Default value. + DISABLED (1): + Natural Language Query Understanding is + disabled. + ENABLED (2): + Natural Language Query Understanding is + enabled. + """ + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + mode: Mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + + +class WorkspaceConfig(proto.Message): + r"""Config to store data store type configuration for workspace + data + + Attributes: + type_ (google.cloud.discoveryengine_v1beta.types.WorkspaceConfig.Type): + The Google Workspace data source. + dasher_customer_id (str): + Obfuscated Dasher customer ID. + super_admin_service_account (str): + Optional. The super admin service account for + the workspace that will be used for access token + generation. For now we only use it for Native + Google Drive connector data ingestion. + super_admin_email_address (str): + Optional. The super admin email address for + the workspace that will be used for access token + generation. For now we only use it for Native + Google Drive connector data ingestion. + """ + + class Type(proto.Enum): + r"""Specifies the type of Workspace App supported by this + DataStore + + Values: + TYPE_UNSPECIFIED (0): + Defaults to an unspecified Workspace type. + GOOGLE_DRIVE (1): + Workspace Data Store contains Drive data + GOOGLE_MAIL (2): + Workspace Data Store contains Mail data + GOOGLE_SITES (3): + Workspace Data Store contains Sites data + GOOGLE_CALENDAR (4): + Workspace Data Store contains Calendar data + GOOGLE_CHAT (5): + Workspace Data Store contains Chat data + GOOGLE_GROUPS (6): + Workspace Data Store contains Groups data + GOOGLE_KEEP (7): + Workspace Data Store contains Keep data + """ + TYPE_UNSPECIFIED = 0 + GOOGLE_DRIVE = 1 + GOOGLE_MAIL = 2 + GOOGLE_SITES = 3 + GOOGLE_CALENDAR = 4 + GOOGLE_CHAT = 5 + GOOGLE_GROUPS = 6 + GOOGLE_KEEP = 7 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + dasher_customer_id: str = proto.Field( + proto.STRING, + number=2, + ) + super_admin_service_account: str = proto.Field( + proto.STRING, + number=4, + ) + super_admin_email_address: str = proto.Field( + proto.STRING, + number=5, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_processing_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_processing_config.py index 2192893da7b4..e7c09c914955 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_processing_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_processing_config.py @@ -29,12 +29,13 @@ class DocumentProcessingConfig(proto.Message): r"""A singleton resource of - [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. It's + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. If it's empty when [DataStore][google.cloud.discoveryengine.v1beta.DataStore] is - created, which defaults to digital parser. The first call to - [DataStoreService.UpdateDocumentProcessingConfig][] method will - initialize the config. + created and + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] is set to + [DataStore.ContentConfig.CONTENT_REQUIRED][google.cloud.discoveryengine.v1beta.DataStore.ContentConfig.CONTENT_REQUIRED], + the default parser will default to digital parser. Attributes: name (str): @@ -62,6 +63,8 @@ class DocumentProcessingConfig(proto.Message): digital parsing and layout parsing are supported. - ``pptx``: Override parsing config for PPTX files, only digital parsing and layout parsing are supported. + - ``xlsm``: Override parsing config for XLSM files, only + digital parsing and layout parsing are supported. - ``xlsx``: Override parsing config for XLSX files, only digital parsing and layout parsing are supported. """ diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_service.py index 39c4a3a68d11..e25ff7a0c94e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/document_service.py @@ -303,11 +303,31 @@ class UrisMatcher(proto.Message): number=1, ) + class FhirMatcher(proto.Message): + r"""Matcher for the + [Document][google.cloud.discoveryengine.v1beta.Document]s by FHIR + resource names. + + Attributes: + fhir_resources (MutableSequence[str]): + Required. The FHIR resources to match by. Format: + projects/{project}/locations/{location}/datasets/{dataset}/fhirStores/{fhir_store}/fhir/{resource_type}/{fhir_resource_id} + """ + + fhir_resources: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + class Matcher(proto.Message): r"""Matcher for the [Document][google.cloud.discoveryengine.v1beta.Document]s. Currently supports matching by exact URIs. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -315,6 +335,10 @@ class Matcher(proto.Message): uris_matcher (google.cloud.discoveryengine_v1beta.types.BatchGetDocumentsMetadataRequest.UrisMatcher): Matcher by exact URIs. + This field is a member of `oneof`_ ``matcher``. + fhir_matcher (google.cloud.discoveryengine_v1beta.types.BatchGetDocumentsMetadataRequest.FhirMatcher): + Matcher by FHIR resource names. + This field is a member of `oneof`_ ``matcher``. """ @@ -324,6 +348,12 @@ class Matcher(proto.Message): oneof="matcher", message="BatchGetDocumentsMetadataRequest.UrisMatcher", ) + fhir_matcher: "BatchGetDocumentsMetadataRequest.FhirMatcher" = proto.Field( + proto.MESSAGE, + number=2, + oneof="matcher", + message="BatchGetDocumentsMetadataRequest.FhirMatcher", + ) parent: str = proto.Field( proto.STRING, @@ -400,6 +430,10 @@ class MatcherValue(proto.Message): r"""The value of the matcher that was used to match the [Document][google.cloud.discoveryengine.v1beta.Document]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -408,6 +442,11 @@ class MatcherValue(proto.Message): If match by URI, the URI of the [Document][google.cloud.discoveryengine.v1beta.Document]. + This field is a member of `oneof`_ ``matcher_value``. + fhir_resource (str): + Format: + projects/{project}/locations/{location}/datasets/{dataset}/fhirStores/{fhir_store}/fhir/{resource_type}/{fhir_resource_id} + This field is a member of `oneof`_ ``matcher_value``. """ @@ -416,6 +455,11 @@ class MatcherValue(proto.Message): number=1, oneof="matcher_value", ) + fhir_resource: str = proto.Field( + proto.STRING, + number=2, + oneof="matcher_value", + ) matcher_value: "BatchGetDocumentsMetadataResponse.DocumentMetadata.MatcherValue" = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/engine.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/engine.py index 59b81842de63..bb1d3868ee91 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/engine.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/engine.py @@ -71,7 +71,7 @@ class Engine(proto.Message): limit of 1024 characters. Format: - ``projects/{project_number}/locations/{location}/collections/{collection}/engines/{engine}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` engine should be 1-63 characters, and valid characters are /[a-z0-9][a-z0-9-_]*/. Otherwise, an INVALID_ARGUMENT error is returned. @@ -120,6 +120,9 @@ class Engine(proto.Message): common_config (google.cloud.discoveryengine_v1beta.types.Engine.CommonConfig): Common config spec that specifies the metadata of the engine. + disable_analytics (bool): + Optional. Whether to disable analytics for + searches performed on this engine. """ class SearchEngineConfig(proto.Message): @@ -335,6 +338,10 @@ class ChatEngineMetadata(proto.Message): number=15, message=CommonConfig, ) + disable_analytics: bool = proto.Field( + proto.BOOL, + number=26, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/engine_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/engine_service.py index 290ed0392a6b..ff0ee8e75d9e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/engine_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/engine_service.py @@ -291,7 +291,7 @@ class PauseEngineRequest(proto.Message): Attributes: name (str): Required. The name of the engine to pause. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` """ name: str = proto.Field( @@ -306,7 +306,7 @@ class ResumeEngineRequest(proto.Message): Attributes: name (str): Required. The name of the engine to resume. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` """ name: str = proto.Field( @@ -322,7 +322,7 @@ class TuneEngineRequest(proto.Message): Attributes: name (str): Required. The resource name of the engine to tune. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` """ name: str = proto.Field( @@ -338,7 +338,7 @@ class TuneEngineMetadata(proto.Message): engine (str): Required. The resource name of the engine that this tune applies to. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`` """ engine: str = proto.Field( diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/grounded_generation_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/grounded_generation_service.py index cbdefdb249b3..ee0d3f595a4e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/grounded_generation_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/grounded_generation_service.py @@ -24,6 +24,9 @@ __protobuf__ = proto.module( package="google.cloud.discoveryengine.v1beta", manifest={ + "GroundedGenerationContent", + "GenerateGroundedContentRequest", + "GenerateGroundedContentResponse", "CheckGroundingSpec", "CheckGroundingRequest", "CheckGroundingResponse", @@ -31,6 +34,690 @@ ) +class GroundedGenerationContent(proto.Message): + r"""Base structured datatype containing multi-part content of a + message. + + Attributes: + role (str): + Producer of the content. Must be either ``user`` or + ``model``. + + Intended to be used for multi-turn conversations. Otherwise, + it can be left unset. + parts (MutableSequence[google.cloud.discoveryengine_v1beta.types.GroundedGenerationContent.Part]): + Ordered ``Parts`` that constitute a single message. + """ + + class Part(proto.Message): + r"""Single part of content. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + Inline text. + + This field is a member of `oneof`_ ``data``. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="data", + ) + + role: str = proto.Field( + proto.STRING, + number=1, + ) + parts: MutableSequence[Part] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Part, + ) + + +class GenerateGroundedContentRequest(proto.Message): + r"""Top-level message sent by the client for the + ``GenerateGroundedContent`` method. + + Attributes: + location (str): + Required. Location resource. + + Format: ``projects/{project}/locations/{location}``. + system_instruction (google.cloud.discoveryengine_v1beta.types.GroundedGenerationContent): + Content of the system instruction for the + current API. + These instructions will take priority over any + other prompt instructions if the selected model + is supporting them. + contents (MutableSequence[google.cloud.discoveryengine_v1beta.types.GroundedGenerationContent]): + Content of the current conversation with the + model. + For single-turn queries, this is a single + instance. For multi-turn queries, this is a + repeated field that contains conversation + history + latest request. + generation_spec (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GenerationSpec): + Content generation specification. + grounding_spec (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSpec): + Grounding specification. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + class GenerationSpec(proto.Message): + r"""Content generation specification. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model_id (str): + Specifies which Vertex model id to use for + generation. + language_code (str): + Language code for content. Use language tags defined by + `BCP47 `__. + temperature (float): + If specified, custom value for the + temperature will be used. + + This field is a member of `oneof`_ ``_temperature``. + top_p (float): + If specified, custom value for nucleus + sampling will be used. + + This field is a member of `oneof`_ ``_top_p``. + top_k (int): + If specified, custom value for top-k sampling + will be used. + + This field is a member of `oneof`_ ``_top_k``. + frequency_penalty (float): + If specified, custom value for frequency + penalty will be used. + + This field is a member of `oneof`_ ``_frequency_penalty``. + presence_penalty (float): + If specified, custom value for presence + penalty will be used. + + This field is a member of `oneof`_ ``_presence_penalty``. + max_output_tokens (int): + If specified, custom value for max output + tokens will be used. + + This field is a member of `oneof`_ ``_max_output_tokens``. + """ + + model_id: str = proto.Field( + proto.STRING, + number=3, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) + temperature: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + top_p: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + top_k: int = proto.Field( + proto.INT32, + number=7, + optional=True, + ) + frequency_penalty: float = proto.Field( + proto.FLOAT, + number=8, + optional=True, + ) + presence_penalty: float = proto.Field( + proto.FLOAT, + number=9, + optional=True, + ) + max_output_tokens: int = proto.Field( + proto.INT32, + number=10, + optional=True, + ) + + class DynamicRetrievalConfiguration(proto.Message): + r"""Describes the options to customize dynamic retrieval. + + Attributes: + predictor (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor): + Specification for the predictor for dynamic + retrieval. + """ + + class DynamicRetrievalPredictor(proto.Message): + r"""Describes the predictor settings for dynamic retrieval. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + version (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor.Version): + The version of the predictor to be used in + dynamic retrieval. + threshold (float): + The value of the threshold. If the predictor + will predict a value smaller than this, it would + suppress grounding in the source. + + This field is a member of `oneof`_ ``_threshold``. + """ + + class Version(proto.Enum): + r"""The version of the predictor to be used in dynamic retrieval. + + Values: + VERSION_UNSPECIFIED (0): + Automatically choose the best version of the + retrieval predictor. + V1_INDEPENDENT (1): + The V1 model which is evaluating each source + independently. + """ + VERSION_UNSPECIFIED = 0 + V1_INDEPENDENT = 1 + + version: "GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor.Version" = proto.Field( + proto.ENUM, + number=1, + enum="GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor.Version", + ) + threshold: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + predictor: "GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor" = proto.Field( + proto.MESSAGE, + number=1, + message="GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor", + ) + + class GroundingSource(proto.Message): + r"""Grounding source. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_source (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSource.InlineSource): + If set, grounding is performed with inline + content. + + This field is a member of `oneof`_ ``source``. + search_source (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSource.SearchSource): + If set, grounding is performed with Vertex AI + Search. + + This field is a member of `oneof`_ ``source``. + google_search_source (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource): + If set, grounding is performed with Google + Search. + + This field is a member of `oneof`_ ``source``. + """ + + class InlineSource(proto.Message): + r"""Message to be used for grounding based on inline content. + + Attributes: + grounding_facts (MutableSequence[google.cloud.discoveryengine_v1beta.types.GroundingFact]): + List of facts to be used for grounding. + attributes (MutableMapping[str, str]): + Attributes associated with the content. + + Common attributes include ``source`` (indicating where the + content was sourced from) and ``author`` (indicating the + author of the content). + """ + + grounding_facts: MutableSequence[ + grounding.GroundingFact + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=grounding.GroundingFact, + ) + attributes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + class SearchSource(proto.Message): + r"""Message to be used for grounding with Vertex AI Search. + + Attributes: + serving_config (str): + The resource name of the Engine to use. + + Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}/servingConfigs/{serving_config_id}`` + max_result_count (int): + Number of search results to return. + + The default value is 10. The maximumm allowed + value is 10. + filter (str): + Filter expression to be applied to the search. + + The syntax is the same as + [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter]. + safe_search (bool): + If set, safe search is enabled in Vertex AI + Search requests. + """ + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + max_result_count: int = proto.Field( + proto.INT32, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=5, + ) + + class GoogleSearchSource(proto.Message): + r"""Google Search config parameters. + + Attributes: + dynamic_retrieval_config (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.DynamicRetrievalConfiguration): + Optional. Specifies the dynamic retrieval + configuration for the given source. + """ + + dynamic_retrieval_config: "GenerateGroundedContentRequest.DynamicRetrievalConfiguration" = proto.Field( + proto.MESSAGE, + number=2, + message="GenerateGroundedContentRequest.DynamicRetrievalConfiguration", + ) + + inline_source: "GenerateGroundedContentRequest.GroundingSource.InlineSource" = ( + proto.Field( + proto.MESSAGE, + number=1, + oneof="source", + message="GenerateGroundedContentRequest.GroundingSource.InlineSource", + ) + ) + search_source: "GenerateGroundedContentRequest.GroundingSource.SearchSource" = ( + proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message="GenerateGroundedContentRequest.GroundingSource.SearchSource", + ) + ) + google_search_source: "GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource" = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message="GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource", + ) + + class GroundingSpec(proto.Message): + r"""Grounding specification. + + Attributes: + grounding_sources (MutableSequence[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest.GroundingSource]): + Grounding sources. + """ + + grounding_sources: MutableSequence[ + "GenerateGroundedContentRequest.GroundingSource" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="GenerateGroundedContentRequest.GroundingSource", + ) + + location: str = proto.Field( + proto.STRING, + number=1, + ) + system_instruction: "GroundedGenerationContent" = proto.Field( + proto.MESSAGE, + number=5, + message="GroundedGenerationContent", + ) + contents: MutableSequence["GroundedGenerationContent"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="GroundedGenerationContent", + ) + generation_spec: GenerationSpec = proto.Field( + proto.MESSAGE, + number=3, + message=GenerationSpec, + ) + grounding_spec: GroundingSpec = proto.Field( + proto.MESSAGE, + number=4, + message=GroundingSpec, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + + +class GenerateGroundedContentResponse(proto.Message): + r"""Response for the ``GenerateGroundedContent`` method. + + Attributes: + candidates (MutableSequence[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate]): + Generated candidates. + """ + + class Candidate(proto.Message): + r"""A response candidate generated from the model. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + index (int): + Index of the candidate. + content (google.cloud.discoveryengine_v1beta.types.GroundedGenerationContent): + Content of the candidate. + grounding_score (float): + The overall grounding score for the candidate, in the range + of [0, 1]. + + This field is a member of `oneof`_ ``_grounding_score``. + grounding_metadata (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata): + Grounding metadata for the generated content. + """ + + class GroundingMetadata(proto.Message): + r"""Citation for the generated content. + + Attributes: + retrieval_metadata (MutableSequence[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata]): + Retrieval metadata to provide an + understanding in the retrieval steps performed + by the model. There can be multiple such + messages which can correspond to different parts + of the retrieval. This is a mechanism used to + ensure transparency to our users. + support_chunks (MutableSequence[google.cloud.discoveryengine_v1beta.types.FactChunk]): + List of chunks to be attributed across all + claims in the candidate. These are derived from + the grounding sources supplied in the request. + web_search_queries (MutableSequence[str]): + Web search queries for the following-up web + search. + search_entry_point (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.SearchEntryPoint): + Google search entry for the following-up web + searches. + grounding_support (MutableSequence[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.GroundingSupport]): + GroundingSupport across all claims in the + answer candidate. An support to a fact indicates + that the claim is supported by the fact. + """ + + class RetrievalMetadata(proto.Message): + r"""Describes the metadata associated with a retrieval step. + + Attributes: + source (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata.Source): + Describes the source to which the metadata is + referring to. + dynamic_retrieval_metadata (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalMetadata): + Metadata for dynamic retrieval. + """ + + class Source(proto.Enum): + r"""Describes the source to which the metadata is associated to. + + Values: + SOURCE_UNSPECIFIED (0): + Unspecified source. + VERTEX_AI_SEARCH (1): + Vertex AI search. + GOOGLE_SEARCH (3): + Google Search. + INLINE_CONTENT (2): + User inline provided content. + GOOGLE_MAPS (4): + Google Maps. + """ + SOURCE_UNSPECIFIED = 0 + VERTEX_AI_SEARCH = 1 + GOOGLE_SEARCH = 3 + INLINE_CONTENT = 2 + GOOGLE_MAPS = 4 + + source: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata.Source" = proto.Field( + proto.ENUM, + number=1, + enum="GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata.Source", + ) + dynamic_retrieval_metadata: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalMetadata" = proto.Field( + proto.MESSAGE, + number=2, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalMetadata", + ) + + class DynamicRetrievalMetadata(proto.Message): + r"""Describes the metadata about dynamic retrieval. + + Attributes: + predictor_metadata (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata): + Metadata for the dynamic retrieval predictor. + """ + + predictor_metadata: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata" = proto.Field( + proto.MESSAGE, + number=1, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata", + ) + + class DynamicRetrievalPredictorMetadata(proto.Message): + r"""Describes the metadata about the dynamic retrieval predictor. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + version (google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata.Version): + The version of the predictor which was used + in dynamic retrieval. + prediction (float): + The value of the predictor. This should be between [0, 1] + where a value of 0 means that the query would not benefit + from grounding, while a value of 1.0 means that the query + would benefit the most. In between values allow to + differentiate between different usefulness scores for + grounding. + + This field is a member of `oneof`_ ``_prediction``. + """ + + class Version(proto.Enum): + r"""The version of the predictor which was used in dynamic + retrieval. + + Values: + VERSION_UNSPECIFIED (0): + Unspecified version, should never be used. + V1_INDEPENDENT (1): + The V1 model which is evaluating each source + independently. + """ + VERSION_UNSPECIFIED = 0 + V1_INDEPENDENT = 1 + + version: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata.Version" = proto.Field( + proto.ENUM, + number=1, + enum="GenerateGroundedContentResponse.Candidate.GroundingMetadata.DynamicRetrievalPredictorMetadata.Version", + ) + prediction: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + class SearchEntryPoint(proto.Message): + r"""Google search entry point. + + Attributes: + rendered_content (str): + Web content snippet that can be embedded in a + web page or an app webview. + sdk_blob (bytes): + Base64 encoded JSON representing array of + tuple. + """ + + rendered_content: str = proto.Field( + proto.STRING, + number=1, + ) + sdk_blob: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + class GroundingSupport(proto.Message): + r"""Grounding info for a claim in the candidate and its support. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + claim_text (str): + Text for the claim in the candidate. Always + provided when a support is found. + support_chunk_indices (MutableSequence[int]): + A list of indices (into 'support_chunks') specifying the + citations associated with the claim. For instance [1,3,4] + means that support_chunks[1], support_chunks[3], + support_chunks[4] are the chunks attributed to the claim. + support_score (float): + A score in the range of [0, 1] describing how grounded is a + specific claim in the support chunks indicated. Higher value + means that the claim is better supported by the chunks. + + This field is a member of `oneof`_ ``_support_score``. + """ + + claim_text: str = proto.Field( + proto.STRING, + number=1, + ) + support_chunk_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=3, + ) + support_score: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + retrieval_metadata: MutableSequence[ + "GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata" + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata", + ) + support_chunks: MutableSequence[grounding.FactChunk] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=grounding.FactChunk, + ) + web_search_queries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + search_entry_point: "GenerateGroundedContentResponse.Candidate.GroundingMetadata.SearchEntryPoint" = proto.Field( + proto.MESSAGE, + number=4, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.SearchEntryPoint", + ) + grounding_support: MutableSequence[ + "GenerateGroundedContentResponse.Candidate.GroundingMetadata.GroundingSupport" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.GroundingSupport", + ) + + index: int = proto.Field( + proto.INT32, + number=1, + ) + content: "GroundedGenerationContent" = proto.Field( + proto.MESSAGE, + number=2, + message="GroundedGenerationContent", + ) + grounding_score: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) + grounding_metadata: "GenerateGroundedContentResponse.Candidate.GroundingMetadata" = proto.Field( + proto.MESSAGE, + number=4, + message="GenerateGroundedContentResponse.Candidate.GroundingMetadata", + ) + + candidates: MutableSequence[Candidate] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Candidate, + ) + + class CheckGroundingSpec(proto.Message): r"""Specification for the grounding check. @@ -65,8 +752,8 @@ class CheckGroundingRequest(proto.Message): Required. The resource name of the grounding config, such as ``projects/*/locations/global/groundingConfigs/default_grounding_config``. answer_candidate (str): - Answer candidate to check. Can have a maximum - length of 1024 characters. + Answer candidate to check. It can have a + maximum length of 4096 tokens. facts (MutableSequence[google.cloud.discoveryengine_v1beta.types.GroundingFact]): List of facts for the grounding check. We support up to 200 facts. @@ -142,11 +829,29 @@ class CheckGroundingResponse(proto.Message): List of facts cited across all claims in the answer candidate. These are derived from the facts supplied in the request. + cited_facts (MutableSequence[google.cloud.discoveryengine_v1beta.types.CheckGroundingResponse.CheckGroundingFactChunk]): + List of facts cited across all claims in the + answer candidate. These are derived from the + facts supplied in the request. claims (MutableSequence[google.cloud.discoveryengine_v1beta.types.CheckGroundingResponse.Claim]): Claim texts and citation info across all claims in the answer candidate. """ + class CheckGroundingFactChunk(proto.Message): + r"""Fact chunk for grounding check. + + Attributes: + chunk_text (str): + Text content of the fact chunk. Can be at + most 10K characters long. + """ + + chunk_text: str = proto.Field( + proto.STRING, + number=1, + ) + class Claim(proto.Message): r"""Text and citation info for a claim in the answer candidate. @@ -222,6 +927,11 @@ class Claim(proto.Message): number=3, message=grounding.FactChunk, ) + cited_facts: MutableSequence[CheckGroundingFactChunk] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=CheckGroundingFactChunk, + ) claims: MutableSequence[Claim] = proto.RepeatedField( proto.MESSAGE, number=4, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/grounding.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/grounding.py index 571f86b91515..9b0857db7c2d 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/grounding.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/grounding.py @@ -22,12 +22,28 @@ __protobuf__ = proto.module( package="google.cloud.discoveryengine.v1beta", manifest={ + "GroundingConfig", "GroundingFact", "FactChunk", }, ) +class GroundingConfig(proto.Message): + r"""Grounding configuration. + + Attributes: + name (str): + Required. Name of the GroundingConfig, of the form + ``projects/{project}/locations/{location}/groundingConfigs/{grounding_config}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class GroundingFact(proto.Message): r"""Grounding Fact. diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/project.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/project.py index 21e39ec3fc5c..c5099a702284 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/project.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/project.py @@ -35,9 +35,9 @@ class Project(proto.Message): Attributes: name (str): Output only. Full resource name of the project, for example - ``projects/{project_number}``. Note that when making - requests, project number and project id are both acceptable, - but the server will always respond in project number. + ``projects/{project}``. Note that when making requests, + project number and project id are both acceptable, but the + server will always respond in project number. create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The timestamp when this project is created. diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/purge_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/purge_config.py index 829032161fdd..f416f4d2bdba 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/purge_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/purge_config.py @@ -50,7 +50,7 @@ class PurgeUserEventsRequest(proto.Message): parent (str): Required. The resource name of the catalog under which the events are created. The format is - ``projects/${projectId}/locations/global/collections/{$collectionId}/dataStores/${dataStoreId}`` + ``projects/{project}/locations/global/collections/{collection}/dataStores/{dataStore}``. filter (str): Required. The filter string to specify the events to be deleted with a length limit of 5,000 characters. The diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/rank_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/rank_service.py index b1da68f767e7..5b551ae97edc 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/rank_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/rank_service.py @@ -81,7 +81,7 @@ class RankRequest(proto.Message): ranking_config (str): Required. The resource name of the rank service config, such as - ``projects/{project_num}/locations/{location_id}/rankingConfigs/default_ranking_config``. + ``projects/{project_num}/locations/{location}/rankingConfigs/default_ranking_config``. model (str): The identifier of the model to use. It is one of: diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/search_service.py index 8db64de1bb12..06ec03284fc8 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/search_service.py @@ -92,6 +92,10 @@ class SearchRequest(proto.Message): If this field is negative, an ``INVALID_ARGUMENT`` is returned. + one_box_page_size (int): + The maximum number of results to return for + OneBox. This applies to each OneBox type + individually. Default number is 10. data_store_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.DataStoreSpec]): Specs defining dataStores to filter on in a search call and configurations for those @@ -339,6 +343,17 @@ class SearchRequest(proto.Message): a balance of precision and recall to deliver both highly accurate results and comprehensive coverage of relevant information. + personalization_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.PersonalizationSpec): + The specification for personalization. + + Notice that if both + [ServingConfig.personalization_spec][google.cloud.discoveryengine.v1beta.ServingConfig.personalization_spec] + and + [SearchRequest.personalization_spec][google.cloud.discoveryengine.v1beta.SearchRequest.personalization_spec] + are set, + [SearchRequest.personalization_spec][google.cloud.discoveryengine.v1beta.SearchRequest.personalization_spec] + overrides + [ServingConfig.personalization_spec][google.cloud.discoveryengine.v1beta.ServingConfig.personalization_spec]. """ class RelevanceThreshold(proto.Enum): @@ -395,12 +410,21 @@ class DataStoreSpec(proto.Message): [DataStore][google.cloud.discoveryengine.v1beta.DataStore], such as ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + filter (str): + Optional. Filter specification to filter documents in the + data store specified by data_store field. For more + information on filtering, see + `Filtering `__ """ data_store: str = proto.Field( proto.STRING, number=1, ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) class FacetSpec(proto.Message): r"""A facet specification to perform faceted search. @@ -1022,6 +1046,19 @@ class SummarySpec(proto.Message): used regardless of relevance to generate answers. If set to ``true``, only queries with high relevance search results will generate answers. + ignore_jail_breaking_query (bool): + Optional. Specifies whether to filter out jail-breaking + queries. The default value is ``false``. + + Google employs search-query classification to detect + jail-breaking queries. No summary is returned if the search + query is classified as a jail-breaking query. A user might + add instructions to the query to change the tone, style, + language, content of the answer, or ask the model to act as + a different entity, e.g. "Reply in the tone of a competing + company's CEO". If this field is set to ``true``, we skip + generating summaries for jail-breaking queries and return + fallback messages instead. model_prompt_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec): If specified, the spec will be used to modify the prompt provided to the LLM. @@ -1103,6 +1140,10 @@ class ModelSpec(proto.Message): proto.BOOL, number=9, ) + ignore_jail_breaking_query: bool = proto.Field( + proto.BOOL, + number=10, + ) model_prompt_spec: "SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec" = proto.Field( proto.MESSAGE, number=5, @@ -1432,6 +1473,38 @@ class SessionSpec(proto.Message): optional=True, ) + class PersonalizationSpec(proto.Message): + r"""The specification for personalization. + + Attributes: + mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.PersonalizationSpec.Mode): + The personalization mode of the search request. Defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. + """ + + class Mode(proto.Enum): + r"""The personalization mode of each search request. + + Values: + MODE_UNSPECIFIED (0): + Default value. In this case, server behavior defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.PersonalizationSpec.Mode.AUTO]. + AUTO (1): + Personalization is enabled if data quality + requirements are met. + DISABLED (2): + Disable personalization. + """ + MODE_UNSPECIFIED = 0 + AUTO = 1 + DISABLED = 2 + + mode: "SearchRequest.PersonalizationSpec.Mode" = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.PersonalizationSpec.Mode", + ) + serving_config: str = proto.Field( proto.STRING, number=1, @@ -1461,6 +1534,10 @@ class SessionSpec(proto.Message): proto.INT32, number=6, ) + one_box_page_size: int = proto.Field( + proto.INT32, + number=47, + ) data_store_specs: MutableSequence[DataStoreSpec] = proto.RepeatedField( proto.MESSAGE, number=32, @@ -1570,6 +1647,11 @@ class SessionSpec(proto.Message): number=44, enum=RelevanceThreshold, ) + personalization_spec: PersonalizationSpec = proto.Field( + proto.MESSAGE, + number=46, + message=PersonalizationSpec, + ) class SearchResponse(proto.Message): @@ -1834,7 +1916,8 @@ class SummarySkippedReason(proto.Enum): NON_SUMMARY_SEEKING_QUERY_IGNORED (2): The non-summary seeking query ignored case. - Only used when + Google skips the summary if the query is chit chat. Only + used when [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] is set to ``true``. OUT_OF_DOMAIN_QUERY_IGNORED (3): @@ -1874,6 +1957,13 @@ class SummarySkippedReason(proto.Enum): Google skips the summary if there is a customer policy violation detected. The policy is defined by the customer. + NON_SUMMARY_SEEKING_QUERY_IGNORED_V2 (9): + The non-answer seeking query ignored case. + + Google skips the summary if the query doesn't have clear + intent. Only used when + [SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_answer_seeking_query] + is set to ``true``. """ SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 ADVERSARIAL_QUERY_IGNORED = 1 @@ -1884,6 +1974,7 @@ class SummarySkippedReason(proto.Enum): NO_RELEVANT_CONTENT = 6 JAIL_BREAKING_QUERY_IGNORED = 7 CUSTOMER_POLICY_VIOLATION = 8 + NON_SUMMARY_SEEKING_QUERY_IGNORED_V2 = 9 class SafetyAttributes(proto.Message): r"""Safety Attribute categories and their associated confidence @@ -2465,11 +2556,15 @@ class OneBoxType(proto.Enum): One Box result contains organization results. SLACK (3): One Box result contains slack results. + KNOWLEDGE_GRAPH (4): + One Box result contains Knowledge Graph + search responses. """ ONE_BOX_TYPE_UNSPECIFIED = 0 PEOPLE = 1 ORGANIZATION = 2 SLACK = 3 + KNOWLEDGE_GRAPH = 4 one_box_type: "SearchResponse.OneBoxResult.OneBoxType" = proto.Field( proto.ENUM, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config.py index 3594a4e4c065..914e934f845b 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config.py @@ -209,6 +209,17 @@ class ServingConfig(proto.Message): controls in the list will execute. Order does not matter. Maximum number of specifications is 100. + personalization_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.PersonalizationSpec): + The specification for personalization spec. + + Notice that if both + [ServingConfig.personalization_spec][google.cloud.discoveryengine.v1beta.ServingConfig.personalization_spec] + and + [SearchRequest.personalization_spec][google.cloud.discoveryengine.v1beta.SearchRequest.personalization_spec] + are set, + [SearchRequest.personalization_spec][google.cloud.discoveryengine.v1beta.SearchRequest.personalization_spec] + overrides + [ServingConfig.personalization_spec][google.cloud.discoveryengine.v1beta.ServingConfig.personalization_spec]. """ class MediaConfig(proto.Message): @@ -261,6 +272,11 @@ class MediaConfig(proto.Message): If unset, watch history demotion will not be applied. Content freshness demotion will still be applied. + demote_content_watched_past_days (int): + Optional. Specifies the number of days to + look back for demoting watched content. If set + to zero or unset, defaults to the maximum of 365 + days. content_freshness_cutoff_days (int): Specifies the content freshness used for recommendation result. Contents will be demoted @@ -282,6 +298,10 @@ class MediaConfig(proto.Message): proto.STRING, number=1, ) + demote_content_watched_past_days: int = proto.Field( + proto.INT32, + number=37, + ) content_freshness_cutoff_days: int = proto.Field( proto.INT32, number=4, @@ -393,6 +413,13 @@ class GenericConfig(proto.Message): proto.STRING, number=19, ) + personalization_spec: search_service.SearchRequest.PersonalizationSpec = ( + proto.Field( + proto.MESSAGE, + number=25, + message=search_service.SearchRequest.PersonalizationSpec, + ) + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config_service.py index a63068e9cc34..9ee784f12d3c 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/serving_config_service.py @@ -70,7 +70,7 @@ class GetServingConfigRequest(proto.Message): name (str): Required. The resource name of the ServingConfig to get. Format: - ``projects/{project_number}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}`` """ name: str = proto.Field( @@ -85,7 +85,7 @@ class ListServingConfigsRequest(proto.Message): Attributes: parent (str): Required. Full resource name of the parent resource. Format: - ``projects/{project_number}/locations/{location}/collections/{collection}/engines/{engine}`` + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` page_size (int): Optional. Maximum number of results to return. If unspecified, defaults to 100. If a diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/site_search_engine.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/site_search_engine.py index dbf6bac68bf7..46e7ce3936e5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/site_search_engine.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/site_search_engine.py @@ -26,6 +26,7 @@ "SiteSearchEngine", "TargetSite", "SiteVerificationInfo", + "Sitemap", }, ) @@ -260,4 +261,40 @@ class SiteVerificationState(proto.Enum): ) +class Sitemap(proto.Message): + r"""A sitemap for the SiteSearchEngine. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Public URI for the sitemap, e.g. + ``www.example.com/sitemap.xml``. + + This field is a member of `oneof`_ ``feed``. + name (str): + Output only. The fully qualified resource name of the + sitemap. + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/sitemaps/*`` + The ``sitemap_id`` suffix is system-generated. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The sitemap's creation time. + """ + + uri: str = proto.Field( + proto.STRING, + number=2, + oneof="feed", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/site_search_engine_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/site_search_engine_service.py index a54aec94ea33..b345cfa1d326 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/site_search_engine_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/site_search_engine_service.py @@ -40,6 +40,12 @@ "ListTargetSitesResponse", "BatchCreateTargetSiteMetadata", "BatchCreateTargetSitesResponse", + "CreateSitemapRequest", + "DeleteSitemapRequest", + "FetchSitemapsRequest", + "CreateSitemapMetadata", + "DeleteSitemapMetadata", + "FetchSitemapsResponse", "EnableAdvancedSiteSearchRequest", "EnableAdvancedSiteSearchResponse", "EnableAdvancedSiteSearchMetadata", @@ -427,6 +433,217 @@ class BatchCreateTargetSitesResponse(proto.Message): ) +class CreateSitemapRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + method. + + Attributes: + parent (str): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + sitemap (google.cloud.discoveryengine_v1beta.types.Sitemap): + Required. The + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + sitemap: gcd_site_search_engine.Sitemap = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_site_search_engine.Sitemap, + ) + + +class DeleteSitemapRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + method. + + Attributes: + name (str): + Required. Full resource name of + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], such + as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}``. + + If the caller does not have permission to access the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] does + not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchSitemapsRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + Attributes: + parent (str): + Required. Parent resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1beta.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + matcher (google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest.Matcher): + Optional. If specified, fetches the matching + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s. If + not specified, fetches all + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s in + the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + """ + + class UrisMatcher(proto.Message): + r"""Matcher for the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s by their + uris. + + Attributes: + uris (MutableSequence[str]): + The [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + uris. + """ + + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class Matcher(proto.Message): + r"""Matcher for the + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s. Currently + only supports uris matcher. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uris_matcher (google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest.UrisMatcher): + Matcher by sitemap URIs. + + This field is a member of `oneof`_ ``matcher``. + """ + + uris_matcher: "FetchSitemapsRequest.UrisMatcher" = proto.Field( + proto.MESSAGE, + number=1, + oneof="matcher", + message="FetchSitemapsRequest.UrisMatcher", + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + matcher: Matcher = proto.Field( + proto.MESSAGE, + number=2, + message=Matcher, + ) + + +class CreateSitemapMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.CreateSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteSitemapMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.DeleteSitemap][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class FetchSitemapsResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.FetchSitemaps][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps] + method. + + Attributes: + sitemaps_metadata (MutableSequence[google.cloud.discoveryengine_v1beta.types.FetchSitemapsResponse.SitemapMetadata]): + List of + [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]s + fetched. + """ + + class SitemapMetadata(proto.Message): + r"""Contains a [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap] + and its metadata. + + Attributes: + sitemap (google.cloud.discoveryengine_v1beta.types.Sitemap): + The [Sitemap][google.cloud.discoveryengine.v1beta.Sitemap]. + """ + + sitemap: gcd_site_search_engine.Sitemap = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_site_search_engine.Sitemap, + ) + + sitemaps_metadata: MutableSequence[SitemapMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SitemapMetadata, + ) + + class EnableAdvancedSiteSearchRequest(proto.Message): r"""Request message for [SiteSearchEngineService.EnableAdvancedSiteSearch][google.cloud.discoveryengine.v1beta.SiteSearchEngineService.EnableAdvancedSiteSearch] @@ -550,6 +767,11 @@ class RecrawlUrisRequest(proto.Message): Each URI should match at least one [TargetSite][google.cloud.discoveryengine.v1beta.TargetSite] in ``site_search_engine``. + site_credential (str): + Optional. Full resource name of the [SiteCredential][], such + as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/siteCredentials/*``. + Only set to crawl private URIs. """ site_search_engine: str = proto.Field( @@ -560,6 +782,10 @@ class RecrawlUrisRequest(proto.Message): proto.STRING, number=2, ) + site_credential: str = proto.Field( + proto.STRING, + number=5, + ) class RecrawlUrisResponse(proto.Message): @@ -664,10 +890,20 @@ class RecrawlUrisMetadata(proto.Message): Operation last update time. If the operation is done, this is also the finish time. invalid_uris (MutableSequence[str]): + Unique URIs in the request that have invalid + format. Sample limited to 1000. + invalid_uris_count (int): + Total number of unique URIs in the request + that have invalid format. + uris_not_matching_target_sites (MutableSequence[str]): Unique URIs in the request that don't match any TargetSite in the DataStore, only match TargetSites that haven't been fully indexed, or - match a TargetSite with type EXCLUDE. + match a TargetSite with type EXCLUDE. Sample + limited to 1000. + uris_not_matching_target_sites_count (int): + Total number of URIs that don't match any + TargetSites. valid_uris_count (int): Total number of unique URIs in the request that are not in invalid_uris. @@ -696,6 +932,18 @@ class RecrawlUrisMetadata(proto.Message): proto.STRING, number=3, ) + invalid_uris_count: int = proto.Field( + proto.INT32, + number=8, + ) + uris_not_matching_target_sites: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + uris_not_matching_target_sites_count: int = proto.Field( + proto.INT32, + number=10, + ) valid_uris_count: int = proto.Field( proto.INT32, number=4, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/user_event.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/user_event.py index 5c959d423932..9e821bd7de13 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/user_event.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/user_event.py @@ -56,6 +56,7 @@ class UserEvent(proto.Message): - ``view-home-page``: View of the home page. - ``view-category-page``: View of a category page, e.g. Home > Men > Jeans + - ``add-feedback``: Add a user feedback. Retail-related values: @@ -275,6 +276,9 @@ class UserEvent(proto.Message): other ways. media_info (google.cloud.discoveryengine_v1beta.types.MediaInfo): Media-specific info. + panels (MutableSequence[google.cloud.discoveryengine_v1beta.types.PanelInfo]): + Optional. List of panels associated with this + event. Used for page-level impression data. """ event_type: str = proto.Field( @@ -368,6 +372,11 @@ class UserEvent(proto.Message): number=18, message="MediaInfo", ) + panels: MutableSequence["PanelInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message="PanelInfo", + ) class PageInfo(proto.Message): @@ -648,7 +657,7 @@ class DocumentInfo(proto.Message): name (str): The [Document][google.cloud.discoveryengine.v1beta.Document] resource full name, of the form: - ``projects/{project_id}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` This field is a member of `oneof`_ ``document_descriptor``. uri (str): @@ -732,6 +741,9 @@ class PanelInfo(proto.Message): is set. This field is a member of `oneof`_ ``_total_panels``. + documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.DocumentInfo]): + Optional. The document IDs associated with + this panel. """ panel_id: str = proto.Field( @@ -752,6 +764,11 @@ class PanelInfo(proto.Message): number=5, optional=True, ) + documents: MutableSequence["DocumentInfo"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="DocumentInfo", + ) class MediaInfo(proto.Message): diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_advanced_complete_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_advanced_complete_query_async.py new file mode 100644 index 000000000000..303867a60213 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_advanced_complete_query_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 AdvancedCompleteQuery +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_CompletionService_AdvancedCompleteQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_advanced_complete_query(): + # Create a client + client = discoveryengine_v1beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.AdvancedCompleteQueryRequest( + completion_config="completion_config_value", + query="query_value", + ) + + # Make the request + response = await client.advanced_complete_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_CompletionService_AdvancedCompleteQuery_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_advanced_complete_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_advanced_complete_query_sync.py new file mode 100644 index 000000000000..018c59879f62 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_advanced_complete_query_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 AdvancedCompleteQuery +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_CompletionService_AdvancedCompleteQuery_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 discoveryengine_v1beta + + +def sample_advanced_complete_query(): + # Create a client + client = discoveryengine_v1beta.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.AdvancedCompleteQueryRequest( + completion_config="completion_config_value", + query="query_value", + ) + + # Make the request + response = client.advanced_complete_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_CompletionService_AdvancedCompleteQuery_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_async.py new file mode 100644 index 000000000000..06c5fce7212c --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GenerateGroundedContent +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_GroundedGenerationService_GenerateGroundedContent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_generate_grounded_content(): + # Create a client + client = discoveryengine_v1beta.GroundedGenerationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GenerateGroundedContentRequest( + location="location_value", + ) + + # Make the request + response = await client.generate_grounded_content(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_GroundedGenerationService_GenerateGroundedContent_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_sync.py new file mode 100644 index 000000000000..f3a052aa11a4 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GenerateGroundedContent +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_GroundedGenerationService_GenerateGroundedContent_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 discoveryengine_v1beta + + +def sample_generate_grounded_content(): + # Create a client + client = discoveryengine_v1beta.GroundedGenerationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GenerateGroundedContentRequest( + location="location_value", + ) + + # Make the request + response = client.generate_grounded_content(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_GroundedGenerationService_GenerateGroundedContent_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_async.py new file mode 100644 index 000000000000..b17a7971832a --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 StreamGenerateGroundedContent +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_GroundedGenerationService_StreamGenerateGroundedContent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_stream_generate_grounded_content(): + # Create a client + client = discoveryengine_v1beta.GroundedGenerationServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GenerateGroundedContentRequest( + location="location_value", + ) + + # This method expects an iterator which contains + # 'discoveryengine_v1beta.GenerateGroundedContentRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.stream_generate_grounded_content(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + +# [END discoveryengine_v1beta_generated_GroundedGenerationService_StreamGenerateGroundedContent_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_sync.py new file mode 100644 index 000000000000..c38992226dd3 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 StreamGenerateGroundedContent +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_GroundedGenerationService_StreamGenerateGroundedContent_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 discoveryengine_v1beta + + +def sample_stream_generate_grounded_content(): + # Create a client + client = discoveryengine_v1beta.GroundedGenerationServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GenerateGroundedContentRequest( + location="location_value", + ) + + # This method expects an iterator which contains + # 'discoveryengine_v1beta.GenerateGroundedContentRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.stream_generate_grounded_content(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + +# [END discoveryengine_v1beta_generated_GroundedGenerationService_StreamGenerateGroundedContent_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_lite_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_lite_async.py new file mode 100644 index 000000000000..0fa4286475db --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_lite_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 SearchLite +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_SearchService_SearchLite_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_search_lite(): + # Create a client + client = discoveryengine_v1beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search_lite(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SearchService_SearchLite_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_lite_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_lite_sync.py new file mode 100644 index 000000000000..0b0a5bc3bbc1 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_lite_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 SearchLite +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_SearchService_SearchLite_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 discoveryengine_v1beta + + +def sample_search_lite(): + # Create a client + client = discoveryengine_v1beta.SearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search_lite(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SearchService_SearchLite_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_async.py new file mode 100644 index 000000000000..507f3582996c --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreateSitemap +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_SiteSearchEngineService_CreateSitemap_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_create_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + sitemap = discoveryengine_v1beta.Sitemap() + sitemap.uri = "uri_value" + + request = discoveryengine_v1beta.CreateSitemapRequest( + parent="parent_value", + sitemap=sitemap, + ) + + # Make the request + operation = client.create_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SiteSearchEngineService_CreateSitemap_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_sync.py new file mode 100644 index 000000000000..f750d9666ee6 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreateSitemap +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_SiteSearchEngineService_CreateSitemap_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 discoveryengine_v1beta + + +def sample_create_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + sitemap = discoveryengine_v1beta.Sitemap() + sitemap.uri = "uri_value" + + request = discoveryengine_v1beta.CreateSitemapRequest( + parent="parent_value", + sitemap=sitemap, + ) + + # Make the request + operation = client.create_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SiteSearchEngineService_CreateSitemap_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_async.py new file mode 100644 index 000000000000..b90f3e43d3ce --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeleteSitemap +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_SiteSearchEngineService_DeleteSitemap_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_delete_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSitemapRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SiteSearchEngineService_DeleteSitemap_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_sync.py new file mode 100644 index 000000000000..b6b065ada31e --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeleteSitemap +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_SiteSearchEngineService_DeleteSitemap_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 discoveryengine_v1beta + + +def sample_delete_sitemap(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSitemapRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sitemap(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SiteSearchEngineService_DeleteSitemap_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_async.py new file mode 100644 index 000000000000..5f64f222b953 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 FetchSitemaps +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_SiteSearchEngineService_FetchSitemaps_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_fetch_sitemaps(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.FetchSitemapsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.fetch_sitemaps(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SiteSearchEngineService_FetchSitemaps_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_sync.py new file mode 100644 index 000000000000..ee911484a152 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 FetchSitemaps +# 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_SiteSearchEngineService_FetchSitemaps_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 discoveryengine_v1beta + + +def sample_fetch_sitemaps(): + # Create a client + client = discoveryengine_v1beta.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.FetchSitemapsRequest( + parent="parent_value", + ) + + # Make the request + response = client.fetch_sitemaps(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SiteSearchEngineService_FetchSitemaps_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json index 34c50c09e1b8..205a617ed5db 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.13.2" + "version": "0.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json index 62f17efce74f..0e6c03826505 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.13.2" + "version": "0.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json index 2670fd6e4507..fbeaf064bfbc 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json @@ -8,9 +8,162 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.13.2" + "version": "0.13.3" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceAsyncClient.advanced_complete_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "AdvancedCompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse", + "shortName": "advanced_complete_query" + }, + "description": "Sample for AdvancedCompleteQuery", + "file": "discoveryengine_v1beta_generated_completion_service_advanced_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_CompletionService_AdvancedCompleteQuery_async", + "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": "discoveryengine_v1beta_generated_completion_service_advanced_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceClient.advanced_complete_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.CompletionService.AdvancedCompleteQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "AdvancedCompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.AdvancedCompleteQueryResponse", + "shortName": "advanced_complete_query" + }, + "description": "Sample for AdvancedCompleteQuery", + "file": "discoveryengine_v1beta_generated_completion_service_advanced_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_CompletionService_AdvancedCompleteQuery_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": "discoveryengine_v1beta_generated_completion_service_advanced_complete_query_sync.py" + }, { "canonical": true, "clientMethod": { @@ -7953,26 +8106,22 @@ "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceAsyncClient", - "shortName": "ProjectServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceAsyncClient", + "shortName": "GroundedGenerationServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceAsyncClient.provision_project", + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceAsyncClient.generate_grounded_content", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject", + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService.GenerateGroundedContent", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService", + "shortName": "GroundedGenerationService" }, - "shortName": "ProvisionProject" + "shortName": "GenerateGroundedContent" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ProvisionProjectRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest" }, { "name": "retry", @@ -7987,22 +8136,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "provision_project" + "resultType": "google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse", + "shortName": "generate_grounded_content" }, - "description": "Sample for ProvisionProject", - "file": "discoveryengine_v1beta_generated_project_service_provision_project_async.py", + "description": "Sample for GenerateGroundedContent", + "file": "discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ProjectService_ProvisionProject_async", + "regionTag": "discoveryengine_v1beta_generated_GroundedGenerationService_GenerateGroundedContent_async", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8012,47 +8161,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_project_service_provision_project_async.py" + "title": "discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceClient", - "shortName": "ProjectServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceClient", + "shortName": "GroundedGenerationServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceClient.provision_project", + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceClient.generate_grounded_content", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject", + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService.GenerateGroundedContent", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ProjectService", - "shortName": "ProjectService" + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService", + "shortName": "GroundedGenerationService" }, - "shortName": "ProvisionProject" + "shortName": "GenerateGroundedContent" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ProvisionProjectRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest" }, { "name": "retry", @@ -8067,22 +8212,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "provision_project" + "resultType": "google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse", + "shortName": "generate_grounded_content" }, - "description": "Sample for ProvisionProject", - "file": "discoveryengine_v1beta_generated_project_service_provision_project_sync.py", + "description": "Sample for GenerateGroundedContent", + "file": "discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ProjectService_ProvisionProject_sync", + "regionTag": "discoveryengine_v1beta_generated_GroundedGenerationService_GenerateGroundedContent_sync", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8092,44 +8237,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_project_service_provision_project_sync.py" + "title": "discoveryengine_v1beta_generated_grounded_generation_service_generate_grounded_content_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RankServiceAsyncClient", - "shortName": "RankServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceAsyncClient", + "shortName": "GroundedGenerationServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.RankServiceAsyncClient.rank", + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceAsyncClient.stream_generate_grounded_content", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RankService.Rank", + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService.StreamGenerateGroundedContent", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RankService", - "shortName": "RankService" + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService", + "shortName": "GroundedGenerationService" }, - "shortName": "Rank" + "shortName": "StreamGenerateGroundedContent" }, "parameters": [ { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RankRequest" + "name": "requests", + "type": "Iterator[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest]" }, { "name": "retry", @@ -8144,22 +8289,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RankResponse", - "shortName": "rank" + "resultType": "Iterable[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse]", + "shortName": "stream_generate_grounded_content" }, - "description": "Sample for Rank", - "file": "discoveryengine_v1beta_generated_rank_service_rank_async.py", + "description": "Sample for StreamGenerateGroundedContent", + "file": "discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RankService_Rank_async", + "regionTag": "discoveryengine_v1beta_generated_GroundedGenerationService_StreamGenerateGroundedContent_async", "segments": [ { - "end": 51, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 62, "start": 27, "type": "SHORT" }, @@ -8169,43 +8314,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 55, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 58, + "start": 56, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 63, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_rank_service_rank_async.py" + "title": "discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RankServiceClient", - "shortName": "RankServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceClient", + "shortName": "GroundedGenerationServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.RankServiceClient.rank", + "fullName": "google.cloud.discoveryengine_v1beta.GroundedGenerationServiceClient.stream_generate_grounded_content", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RankService.Rank", + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService.StreamGenerateGroundedContent", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RankService", - "shortName": "RankService" + "fullName": "google.cloud.discoveryengine.v1beta.GroundedGenerationService", + "shortName": "GroundedGenerationService" }, - "shortName": "Rank" + "shortName": "StreamGenerateGroundedContent" }, "parameters": [ { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RankRequest" + "name": "requests", + "type": "Iterator[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentRequest]" }, { "name": "retry", @@ -8220,22 +8365,823 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RankResponse", - "shortName": "rank" + "resultType": "Iterable[google.cloud.discoveryengine_v1beta.types.GenerateGroundedContentResponse]", + "shortName": "stream_generate_grounded_content" }, - "description": "Sample for Rank", - "file": "discoveryengine_v1beta_generated_rank_service_rank_sync.py", + "description": "Sample for StreamGenerateGroundedContent", + "file": "discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RankService_Rank_sync", + "regionTag": "discoveryengine_v1beta_generated_GroundedGenerationService_StreamGenerateGroundedContent_sync", "segments": [ { - "end": 51, + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 55, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 56, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_grounded_generation_service_stream_generate_grounded_content_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceAsyncClient", + "shortName": "ProjectServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceAsyncClient.provision_project", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "ProvisionProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ProvisionProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "provision_project" + }, + "description": "Sample for ProvisionProject", + "file": "discoveryengine_v1beta_generated_project_service_provision_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ProjectService_ProvisionProject_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_project_service_provision_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceClient", + "shortName": "ProjectServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ProjectServiceClient.provision_project", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ProjectService.ProvisionProject", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ProjectService", + "shortName": "ProjectService" + }, + "shortName": "ProvisionProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ProvisionProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "provision_project" + }, + "description": "Sample for ProvisionProject", + "file": "discoveryengine_v1beta_generated_project_service_provision_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ProjectService_ProvisionProject_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_project_service_provision_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.RankServiceAsyncClient", + "shortName": "RankServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.RankServiceAsyncClient.rank", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.RankService.Rank", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.RankService", + "shortName": "RankService" + }, + "shortName": "Rank" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.RankRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.RankResponse", + "shortName": "rank" + }, + "description": "Sample for Rank", + "file": "discoveryengine_v1beta_generated_rank_service_rank_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_RankService_Rank_async", + "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": "discoveryengine_v1beta_generated_rank_service_rank_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.RankServiceClient", + "shortName": "RankServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.RankServiceClient.rank", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.RankService.Rank", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.RankService", + "shortName": "RankService" + }, + "shortName": "Rank" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.RankRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.RankResponse", + "shortName": "rank" + }, + "description": "Sample for Rank", + "file": "discoveryengine_v1beta_generated_rank_service_rank_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_RankService_Rank_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": "discoveryengine_v1beta_generated_rank_service_rank_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient", + "shortName": "RecommendationServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient.recommend", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", + "shortName": "RecommendationService" + }, + "shortName": "Recommend" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", + "shortName": "recommend" + }, + "description": "Sample for Recommend", + "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient", + "shortName": "RecommendationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient.recommend", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", + "shortName": "RecommendationService" + }, + "shortName": "Recommend" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", + "shortName": "recommend" + }, + "description": "Sample for Recommend", + "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.create_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "CreateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQueryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + }, + { + "name": "sample_query_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", + "shortName": "create_sample_query" + }, + "description": "Sample for CreateSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_CreateSampleQuery_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.create_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "CreateSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQueryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + }, + { + "name": "sample_query_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", + "shortName": "create_sample_query" + }, + "description": "Sample for CreateSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_CreateSampleQuery_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.delete_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "DeleteSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQueryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_sample_query" + }, + "description": "Sample for DeleteSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_DeleteSampleQuery_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.delete_sample_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" + }, + "shortName": "DeleteSampleQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQueryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_sample_query" + }, + "description": "Sample for DeleteSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_DeleteSampleQuery_sync", + "segments": [ + { + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -8250,39 +9196,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_rank_service_rank_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient", - "shortName": "RecommendationServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", + "shortName": "SampleQueryServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient.recommend", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.get_sample_query", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", - "shortName": "RecommendationService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" }, - "shortName": "Recommend" + "shortName": "GetSampleQuery" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" + "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQueryRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -8297,22 +9245,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", - "shortName": "recommend" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", + "shortName": "get_sample_query" }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py", + "description": "Sample for GetSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_GetSampleQuery_async", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8322,43 +9270,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient", - "shortName": "RecommendationServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", + "shortName": "SampleQueryServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient.recommend", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.get_sample_query", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", - "shortName": "RecommendationService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", + "shortName": "SampleQueryService" }, - "shortName": "Recommend" + "shortName": "GetSampleQuery" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" + "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQueryRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -8373,22 +9325,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", - "shortName": "recommend" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", + "shortName": "get_sample_query" }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py", + "description": "Sample for GetSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_GetSampleQuery_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8398,22 +9350,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py" }, { "canonical": true, @@ -8423,31 +9375,19 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", "shortName": "SampleQueryServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.create_sample_query", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.import_sample_queries", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", "shortName": "SampleQueryService" }, - "shortName": "CreateSampleQuery" + "shortName": "ImportSampleQueries" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQueryRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "sample_query", - "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" - }, - { - "name": "sample_query_id", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.ImportSampleQueriesRequest" }, { "name": "retry", @@ -8462,22 +9402,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", - "shortName": "create_sample_query" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_sample_queries" }, - "description": "Sample for CreateSampleQuery", - "file": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py", + "description": "Sample for ImportSampleQueries", + "file": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_CreateSampleQuery_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ImportSampleQueries_async", "segments": [ { - "end": 56, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 59, "start": 27, "type": "SHORT" }, @@ -8487,22 +9427,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py" }, { "canonical": true, @@ -8511,31 +9451,19 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", "shortName": "SampleQueryServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.create_sample_query", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.import_sample_queries", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.CreateSampleQuery", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", "shortName": "SampleQueryService" }, - "shortName": "CreateSampleQuery" + "shortName": "ImportSampleQueries" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQueryRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "sample_query", - "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" - }, - { - "name": "sample_query_id", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.ImportSampleQueriesRequest" }, { "name": "retry", @@ -8550,22 +9478,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", - "shortName": "create_sample_query" + "resultType": "google.api_core.operation.Operation", + "shortName": "import_sample_queries" }, - "description": "Sample for CreateSampleQuery", - "file": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py", + "description": "Sample for ImportSampleQueries", + "file": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_CreateSampleQuery_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ImportSampleQueries_sync", "segments": [ { - "end": 56, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 59, "start": 27, "type": "SHORT" }, @@ -8575,22 +9503,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_create_sample_query_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py" }, { "canonical": true, @@ -8600,22 +9528,22 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", "shortName": "SampleQueryServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.delete_sample_query", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.list_sample_queries", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", "shortName": "SampleQueryService" }, - "shortName": "DeleteSampleQuery" + "shortName": "ListSampleQueries" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQueryRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQueriesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -8631,21 +9559,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_sample_query" + "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_service.pagers.ListSampleQueriesAsyncPager", + "shortName": "list_sample_queries" }, - "description": "Sample for DeleteSampleQuery", - "file": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py", + "description": "Sample for ListSampleQueries", + "file": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_DeleteSampleQuery_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ListSampleQueries_async", "segments": [ { - "end": 49, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8660,15 +9589,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py" }, { "canonical": true, @@ -8677,22 +9608,22 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", "shortName": "SampleQueryServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.delete_sample_query", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.list_sample_queries", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.DeleteSampleQuery", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", "shortName": "SampleQueryService" }, - "shortName": "DeleteSampleQuery" + "shortName": "ListSampleQueries" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQueryRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQueriesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -8708,21 +9639,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_sample_query" + "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_service.pagers.ListSampleQueriesPager", + "shortName": "list_sample_queries" }, - "description": "Sample for DeleteSampleQuery", - "file": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py", + "description": "Sample for ListSampleQueries", + "file": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_DeleteSampleQuery_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ListSampleQueries_sync", "segments": [ { - "end": 49, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8737,15 +9669,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_delete_sample_query_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py" }, { "canonical": true, @@ -8755,23 +9689,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", "shortName": "SampleQueryServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.get_sample_query", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.update_sample_query", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", "shortName": "SampleQueryService" }, - "shortName": "GetSampleQuery" + "shortName": "UpdateSampleQuery" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQueryRequest" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQueryRequest" }, { - "name": "name", - "type": "str" + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -8787,21 +9725,21 @@ } ], "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", - "shortName": "get_sample_query" + "shortName": "update_sample_query" }, - "description": "Sample for GetSampleQuery", - "file": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py", + "description": "Sample for UpdateSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_GetSampleQuery_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_UpdateSampleQuery_async", "segments": [ { - "end": 51, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 54, "start": 27, "type": "SHORT" }, @@ -8811,22 +9749,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py" }, { "canonical": true, @@ -8835,23 +9773,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", "shortName": "SampleQueryServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.get_sample_query", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.update_sample_query", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.GetSampleQuery", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", "shortName": "SampleQueryService" }, - "shortName": "GetSampleQuery" + "shortName": "UpdateSampleQuery" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQueryRequest" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQueryRequest" }, { - "name": "name", - "type": "str" + "name": "sample_query", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -8867,21 +9809,21 @@ } ], "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", - "shortName": "get_sample_query" + "shortName": "update_sample_query" }, - "description": "Sample for GetSampleQuery", - "file": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py", + "description": "Sample for UpdateSampleQuery", + "file": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_GetSampleQuery_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_UpdateSampleQuery_sync", "segments": [ { - "end": 51, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 54, "start": 27, "type": "SHORT" }, @@ -8891,44 +9833,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_get_sample_query_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", - "shortName": "SampleQueryServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.import_sample_queries", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.create_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", - "shortName": "SampleQueryService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "ImportSampleQueries" + "shortName": "CreateSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ImportSampleQueriesRequest" + "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQuerySetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + }, + { + "name": "sample_query_set_id", + "type": "str" }, { "name": "retry", @@ -8943,22 +9897,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_sample_queries" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "create_sample_query_set" }, - "description": "Sample for ImportSampleQueries", - "file": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py", + "description": "Sample for CreateSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ImportSampleQueries_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_CreateSampleQuerySet_async", "segments": [ { - "end": 59, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 56, "start": 27, "type": "SHORT" }, @@ -8968,43 +9922,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", - "shortName": "SampleQueryServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.import_sample_queries", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.create_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ImportSampleQueries", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", - "shortName": "SampleQueryService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "ImportSampleQueries" + "shortName": "CreateSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ImportSampleQueriesRequest" + "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQuerySetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + }, + { + "name": "sample_query_set_id", + "type": "str" }, { "name": "retry", @@ -9019,22 +9985,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_sample_queries" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "create_sample_query_set" }, - "description": "Sample for ImportSampleQueries", - "file": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py", + "description": "Sample for CreateSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ImportSampleQueries_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_CreateSampleQuerySet_sync", "segments": [ { - "end": 59, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9044,47 +10010,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_import_sample_queries_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", - "shortName": "SampleQueryServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.list_sample_queries", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.delete_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", - "shortName": "SampleQueryService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "ListSampleQueries" + "shortName": "DeleteSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQueriesRequest" + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQuerySetRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9100,22 +10066,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_service.pagers.ListSampleQueriesAsyncPager", - "shortName": "list_sample_queries" + "shortName": "delete_sample_query_set" }, - "description": "Sample for ListSampleQueries", - "file": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py", + "description": "Sample for DeleteSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ListSampleQueries_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_DeleteSampleQuerySet_async", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -9130,41 +10095,39 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", - "shortName": "SampleQueryServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.list_sample_queries", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.delete_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.ListSampleQueries", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", - "shortName": "SampleQueryService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "ListSampleQueries" + "shortName": "DeleteSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQueriesRequest" + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQuerySetRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9180,22 +10143,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_service.pagers.ListSampleQueriesPager", - "shortName": "list_sample_queries" + "shortName": "delete_sample_query_set" }, - "description": "Sample for ListSampleQueries", - "file": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py", + "description": "Sample for DeleteSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_ListSampleQueries_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_DeleteSampleQuerySet_sync", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -9210,47 +10172,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_list_sample_queries_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient", - "shortName": "SampleQueryServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", + "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceAsyncClient.update_sample_query", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.get_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", - "shortName": "SampleQueryService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "UpdateSampleQuery" + "shortName": "GetSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQueryRequest" - }, - { - "name": "sample_query", - "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQuerySetRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -9265,22 +10221,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", - "shortName": "update_sample_query" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "get_sample_query_set" }, - "description": "Sample for UpdateSampleQuery", - "file": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py", + "description": "Sample for GetSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_UpdateSampleQuery_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_GetSampleQuerySet_async", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -9290,51 +10246,47 @@ "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": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient", - "shortName": "SampleQueryServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", + "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQueryServiceClient.update_sample_query", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.get_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService.UpdateSampleQuery", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQueryService", - "shortName": "SampleQueryService" + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", + "shortName": "SampleQuerySetService" }, - "shortName": "UpdateSampleQuery" + "shortName": "GetSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQueryRequest" - }, - { - "name": "sample_query", - "type": "google.cloud.discoveryengine_v1beta.types.SampleQuery" + "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQuerySetRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -9349,22 +10301,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuery", - "shortName": "update_sample_query" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "get_sample_query_set" }, - "description": "Sample for UpdateSampleQuery", - "file": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py", + "description": "Sample for GetSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQueryService_UpdateSampleQuery_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_GetSampleQuerySet_sync", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -9374,22 +10326,22 @@ "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": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_service_update_sample_query_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py" }, { "canonical": true, @@ -9399,32 +10351,24 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.create_sample_query_set", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.list_sample_query_sets", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", "shortName": "SampleQuerySetService" }, - "shortName": "CreateSampleQuerySet" + "shortName": "ListSampleQuerySets" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQuerySetRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "sample_query_set", - "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" - }, - { - "name": "sample_query_set_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9438,22 +10382,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", - "shortName": "create_sample_query_set" + "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_set_service.pagers.ListSampleQuerySetsAsyncPager", + "shortName": "list_sample_query_sets" }, - "description": "Sample for CreateSampleQuerySet", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py", + "description": "Sample for ListSampleQuerySets", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_CreateSampleQuerySet_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_ListSampleQuerySets_async", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -9463,22 +10407,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py" }, { "canonical": true, @@ -9487,32 +10431,24 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.create_sample_query_set", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.list_sample_query_sets", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.CreateSampleQuerySet", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", "shortName": "SampleQuerySetService" }, - "shortName": "CreateSampleQuerySet" + "shortName": "ListSampleQuerySets" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateSampleQuerySetRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "sample_query_set", - "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" - }, - { - "name": "sample_query_set_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9526,22 +10462,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", - "shortName": "create_sample_query_set" + "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_set_service.pagers.ListSampleQuerySetsPager", + "shortName": "list_sample_query_sets" }, - "description": "Sample for CreateSampleQuerySet", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py", + "description": "Sample for ListSampleQuerySets", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_CreateSampleQuerySet_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_ListSampleQuerySets_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -9551,22 +10487,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_create_sample_query_set_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py" }, { "canonical": true, @@ -9576,23 +10512,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", "shortName": "SampleQuerySetServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.delete_sample_query_set", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.update_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", "shortName": "SampleQuerySetService" }, - "shortName": "DeleteSampleQuerySet" + "shortName": "UpdateSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQuerySetRequest" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQuerySetRequest" }, { - "name": "name", - "type": "str" + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -9607,21 +10547,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_sample_query_set" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "update_sample_query_set" }, - "description": "Sample for DeleteSampleQuerySet", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py", + "description": "Sample for UpdateSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_DeleteSampleQuerySet_async", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_UpdateSampleQuerySet_async", "segments": [ { - "end": 49, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 54, "start": 27, "type": "SHORT" }, @@ -9631,20 +10572,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_async.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py" }, { "canonical": true, @@ -9653,23 +10596,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", "shortName": "SampleQuerySetServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.delete_sample_query_set", + "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.update_sample_query_set", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.DeleteSampleQuerySet", + "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", "shortName": "SampleQuerySetService" }, - "shortName": "DeleteSampleQuerySet" + "shortName": "UpdateSampleQuerySet" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteSampleQuerySetRequest" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQuerySetRequest" }, { - "name": "name", - "type": "str" + "name": "sample_query_set", + "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -9684,21 +10631,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_sample_query_set" + "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", + "shortName": "update_sample_query_set" }, - "description": "Sample for DeleteSampleQuerySet", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py", + "description": "Sample for UpdateSampleQuerySet", + "file": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_DeleteSampleQuerySet_sync", + "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_UpdateSampleQuerySet_sync", "segments": [ { - "end": 49, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 54, "start": 27, "type": "SHORT" }, @@ -9708,45 +10656,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_delete_sample_query_set_sync.py" + "title": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", - "shortName": "SampleQuerySetServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.get_sample_query_set", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.create_schema", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", - "shortName": "SampleQuerySetService" + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" }, - "shortName": "GetSampleQuerySet" + "shortName": "CreateSchema" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQuerySetRequest" + "type": "google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "schema", + "type": "google.cloud.discoveryengine_v1beta.types.Schema" + }, + { + "name": "schema_id", "type": "str" }, { @@ -9762,22 +10720,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", - "shortName": "get_sample_query_set" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_schema" }, - "description": "Sample for GetSampleQuerySet", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py", + "description": "Sample for CreateSchema", + "file": "discoveryengine_v1beta_generated_schema_service_create_schema_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_GetSampleQuerySet_async", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_CreateSchema_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9787,46 +10745,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_async.py" + "title": "discoveryengine_v1beta_generated_schema_service_create_schema_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", - "shortName": "SampleQuerySetServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", + "shortName": "SchemaServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.get_sample_query_set", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.create_schema", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.GetSampleQuerySet", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", - "shortName": "SampleQuerySetService" + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" }, - "shortName": "GetSampleQuerySet" + "shortName": "CreateSchema" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetSampleQuerySetRequest" + "type": "google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "schema", + "type": "google.cloud.discoveryengine_v1beta.types.Schema" + }, + { + "name": "schema_id", "type": "str" }, { @@ -9842,22 +10808,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", - "shortName": "get_sample_query_set" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_schema" }, - "description": "Sample for GetSampleQuerySet", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py", + "description": "Sample for CreateSchema", + "file": "discoveryengine_v1beta_generated_schema_service_create_schema_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_GetSampleQuerySet_sync", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_CreateSchema_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -9867,47 +10833,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_get_sample_query_set_sync.py" + "title": "discoveryengine_v1beta_generated_schema_service_create_schema_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", - "shortName": "SampleQuerySetServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.list_sample_query_sets", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.delete_schema", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", - "shortName": "SampleQuerySetService" + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" }, - "shortName": "ListSampleQuerySets" + "shortName": "DeleteSchema" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsRequest" + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9923,22 +10889,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_set_service.pagers.ListSampleQuerySetsAsyncPager", - "shortName": "list_sample_query_sets" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_schema" }, - "description": "Sample for ListSampleQuerySets", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py", + "description": "Sample for DeleteSchema", + "file": "discoveryengine_v1beta_generated_schema_service_delete_schema_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_ListSampleQuerySets_async", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_DeleteSchema_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9953,41 +10919,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_async.py" + "title": "discoveryengine_v1beta_generated_schema_service_delete_schema_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", - "shortName": "SampleQuerySetServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", + "shortName": "SchemaServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.list_sample_query_sets", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.delete_schema", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.ListSampleQuerySets", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", - "shortName": "SampleQuerySetService" + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" }, - "shortName": "ListSampleQuerySets" + "shortName": "DeleteSchema" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListSampleQuerySetsRequest" + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -10003,22 +10969,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.sample_query_set_service.pagers.ListSampleQuerySetsPager", - "shortName": "list_sample_query_sets" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_schema" }, - "description": "Sample for ListSampleQuerySets", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py", + "description": "Sample for DeleteSchema", + "file": "discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_ListSampleQuerySets_sync", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_DeleteSchema_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10033,47 +10999,43 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_list_sample_query_sets_sync.py" + "title": "discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient", - "shortName": "SampleQuerySetServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceAsyncClient.update_sample_query_set", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.get_schema", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.GetSchema", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", - "shortName": "SampleQuerySetService" + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" }, - "shortName": "UpdateSampleQuerySet" + "shortName": "GetSchema" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQuerySetRequest" - }, - { - "name": "sample_query_set", - "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + "type": "google.cloud.discoveryengine_v1beta.types.GetSchemaRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10088,22 +11050,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", - "shortName": "update_sample_query_set" + "resultType": "google.cloud.discoveryengine_v1beta.types.Schema", + "shortName": "get_schema" }, - "description": "Sample for UpdateSampleQuerySet", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py", + "description": "Sample for GetSchema", + "file": "discoveryengine_v1beta_generated_schema_service_get_schema_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_UpdateSampleQuerySet_async", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_GetSchema_async", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10113,51 +11075,47 @@ "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": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_async.py" + "title": "discoveryengine_v1beta_generated_schema_service_get_schema_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient", - "shortName": "SampleQuerySetServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", + "shortName": "SchemaServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SampleQuerySetServiceClient.update_sample_query_set", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.get_schema", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService.UpdateSampleQuerySet", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.GetSchema", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SampleQuerySetService", - "shortName": "SampleQuerySetService" + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" }, - "shortName": "UpdateSampleQuerySet" + "shortName": "GetSchema" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateSampleQuerySetRequest" - }, - { - "name": "sample_query_set", - "type": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet" + "type": "google.cloud.discoveryengine_v1beta.types.GetSchemaRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10172,22 +11130,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.SampleQuerySet", - "shortName": "update_sample_query_set" + "resultType": "google.cloud.discoveryengine_v1beta.types.Schema", + "shortName": "get_schema" }, - "description": "Sample for UpdateSampleQuerySet", - "file": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py", + "description": "Sample for GetSchema", + "file": "discoveryengine_v1beta_generated_schema_service_get_schema_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SampleQuerySetService_UpdateSampleQuerySet_sync", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_GetSchema_sync", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10197,22 +11155,22 @@ "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": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_sample_query_set_service_update_sample_query_set_sync.py" + "title": "discoveryengine_v1beta_generated_schema_service_get_schema_sync.py" }, { "canonical": true, @@ -10222,32 +11180,24 @@ "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", "shortName": "SchemaServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.create_schema", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.list_schemas", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", "shortName": "SchemaService" }, - "shortName": "CreateSchema" + "shortName": "ListSchemas" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListSchemasRequest" }, { "name": "parent", "type": "str" }, - { - "name": "schema", - "type": "google.cloud.discoveryengine_v1beta.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10261,22 +11211,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_schema" + "resultType": "google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasAsyncPager", + "shortName": "list_schemas" }, - "description": "Sample for CreateSchema", - "file": "discoveryengine_v1beta_generated_schema_service_create_schema_async.py", + "description": "Sample for ListSchemas", + "file": "discoveryengine_v1beta_generated_schema_service_list_schemas_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_CreateSchema_async", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_ListSchemas_async", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -10286,22 +11236,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_create_schema_async.py" + "title": "discoveryengine_v1beta_generated_schema_service_list_schemas_async.py" }, { "canonical": true, @@ -10310,32 +11260,24 @@ "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", "shortName": "SchemaServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.create_schema", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.list_schemas", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", "shortName": "SchemaService" }, - "shortName": "CreateSchema" + "shortName": "ListSchemas" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListSchemasRequest" }, { "name": "parent", "type": "str" }, - { - "name": "schema", - "type": "google.cloud.discoveryengine_v1beta.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10349,22 +11291,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_schema" + "resultType": "google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasPager", + "shortName": "list_schemas" }, - "description": "Sample for CreateSchema", - "file": "discoveryengine_v1beta_generated_schema_service_create_schema_sync.py", + "description": "Sample for ListSchemas", + "file": "discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_CreateSchema_sync", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_ListSchemas_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -10374,22 +11316,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_create_schema_sync.py" + "title": "discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py" }, { "canonical": true, @@ -10399,23 +11341,19 @@ "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", "shortName": "SchemaServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.delete_schema", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.update_schema", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", "shortName": "SchemaService" }, - "shortName": "DeleteSchema" + "shortName": "UpdateSchema" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest" }, { "name": "retry", @@ -10431,21 +11369,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_schema" + "shortName": "update_schema" }, - "description": "Sample for DeleteSchema", - "file": "discoveryengine_v1beta_generated_schema_service_delete_schema_async.py", + "description": "Sample for UpdateSchema", + "file": "discoveryengine_v1beta_generated_schema_service_update_schema_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_DeleteSchema_async", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_UpdateSchema_async", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -10455,22 +11393,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_delete_schema_async.py" + "title": "discoveryengine_v1beta_generated_schema_service_update_schema_async.py" }, { "canonical": true, @@ -10479,23 +11417,19 @@ "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", "shortName": "SchemaServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.delete_schema", + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.update_schema", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema", + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", "shortName": "SchemaService" }, - "shortName": "DeleteSchema" + "shortName": "UpdateSchema" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest" }, { "name": "retry", @@ -10511,21 +11445,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_schema" + "shortName": "update_schema" }, - "description": "Sample for DeleteSchema", - "file": "discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py", + "description": "Sample for UpdateSchema", + "file": "discoveryengine_v1beta_generated_schema_service_update_schema_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_DeleteSchema_sync", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_UpdateSchema_sync", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -10535,48 +11469,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py" + "title": "discoveryengine_v1beta_generated_schema_service_update_schema_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.get_schema", + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient.search_lite", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.GetSchema", + "fullName": "google.cloud.discoveryengine.v1beta.SearchService.SearchLite", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" + "fullName": "google.cloud.discoveryengine.v1beta.SearchService", + "shortName": "SearchService" }, - "shortName": "GetSchema" + "shortName": "SearchLite" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" }, { "name": "retry", @@ -10591,22 +11521,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Schema", - "shortName": "get_schema" + "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchLiteAsyncPager", + "shortName": "search_lite" }, - "description": "Sample for GetSchema", - "file": "discoveryengine_v1beta_generated_schema_service_get_schema_async.py", + "description": "Sample for SearchLite", + "file": "discoveryengine_v1beta_generated_search_service_search_lite_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_GetSchema_async", + "regionTag": "discoveryengine_v1beta_generated_SearchService_SearchLite_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -10626,37 +11556,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_get_schema_async.py" + "title": "discoveryengine_v1beta_generated_search_service_search_lite_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", - "shortName": "SchemaServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient", + "shortName": "SearchServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.get_schema", + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient.search_lite", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.GetSchema", + "fullName": "google.cloud.discoveryengine.v1beta.SearchService.SearchLite", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" + "fullName": "google.cloud.discoveryengine.v1beta.SearchService", + "shortName": "SearchService" }, - "shortName": "GetSchema" + "shortName": "SearchLite" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" }, { "name": "retry", @@ -10671,22 +11597,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Schema", - "shortName": "get_schema" + "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchLitePager", + "shortName": "search_lite" }, - "description": "Sample for GetSchema", - "file": "discoveryengine_v1beta_generated_schema_service_get_schema_sync.py", + "description": "Sample for SearchLite", + "file": "discoveryengine_v1beta_generated_search_service_search_lite_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_GetSchema_sync", + "regionTag": "discoveryengine_v1beta_generated_SearchService_SearchLite_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -10706,38 +11632,34 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_get_schema_sync.py" + "title": "discoveryengine_v1beta_generated_search_service_search_lite_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.list_schemas", + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient.search", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas", + "fullName": "google.cloud.discoveryengine.v1beta.SearchService.Search", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" + "fullName": "google.cloud.discoveryengine.v1beta.SearchService", + "shortName": "SearchService" }, - "shortName": "ListSchemas" + "shortName": "Search" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" }, { "name": "retry", @@ -10752,14 +11674,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasAsyncPager", - "shortName": "list_schemas" + "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" }, - "description": "Sample for ListSchemas", - "file": "discoveryengine_v1beta_generated_schema_service_list_schemas_async.py", + "description": "Sample for Search", + "file": "discoveryengine_v1beta_generated_search_service_search_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_ListSchemas_async", + "regionTag": "discoveryengine_v1beta_generated_SearchService_Search_async", "segments": [ { "end": 52, @@ -10792,32 +11714,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_list_schemas_async.py" + "title": "discoveryengine_v1beta_generated_search_service_search_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", - "shortName": "SchemaServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient", + "shortName": "SearchServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.list_schemas", + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient.search", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas", + "fullName": "google.cloud.discoveryengine.v1beta.SearchService.Search", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" + "fullName": "google.cloud.discoveryengine.v1beta.SearchService", + "shortName": "SearchService" }, - "shortName": "ListSchemas" + "shortName": "Search" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" }, { "name": "retry", @@ -10832,14 +11750,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasPager", - "shortName": "list_schemas" + "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchPager", + "shortName": "search" }, - "description": "Sample for ListSchemas", - "file": "discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py", + "description": "Sample for Search", + "file": "discoveryengine_v1beta_generated_search_service_search_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_ListSchemas_sync", + "regionTag": "discoveryengine_v1beta_generated_SearchService_Search_sync", "segments": [ { "end": 52, @@ -10872,29 +11790,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py" + "title": "discoveryengine_v1beta_generated_search_service_search_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceAsyncClient", + "shortName": "SearchTuningServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.update_schema", + "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceAsyncClient.list_custom_models", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema", + "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService.ListCustomModels", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" + "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService", + "shortName": "SearchTuningService" }, - "shortName": "UpdateSchema" + "shortName": "ListCustomModels" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListCustomModelsRequest" }, { "name": "retry", @@ -10909,22 +11827,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_schema" + "resultType": "google.cloud.discoveryengine_v1beta.types.ListCustomModelsResponse", + "shortName": "list_custom_models" }, - "description": "Sample for UpdateSchema", - "file": "discoveryengine_v1beta_generated_schema_service_update_schema_async.py", + "description": "Sample for ListCustomModels", + "file": "discoveryengine_v1beta_generated_search_tuning_service_list_custom_models_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_UpdateSchema_async", + "regionTag": "discoveryengine_v1beta_generated_SearchTuningService_ListCustomModels_async", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10934,43 +11852,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_update_schema_async.py" + "title": "discoveryengine_v1beta_generated_search_tuning_service_list_custom_models_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", - "shortName": "SchemaServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceClient", + "shortName": "SearchTuningServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.update_schema", + "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceClient.list_custom_models", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema", + "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService.ListCustomModels", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" + "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService", + "shortName": "SearchTuningService" }, - "shortName": "UpdateSchema" + "shortName": "ListCustomModels" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListCustomModelsRequest" }, { "name": "retry", @@ -10985,22 +11903,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_schema" + "resultType": "google.cloud.discoveryengine_v1beta.types.ListCustomModelsResponse", + "shortName": "list_custom_models" }, - "description": "Sample for UpdateSchema", - "file": "discoveryengine_v1beta_generated_schema_service_update_schema_sync.py", + "description": "Sample for ListCustomModels", + "file": "discoveryengine_v1beta_generated_search_tuning_service_list_custom_models_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_UpdateSchema_sync", + "regionTag": "discoveryengine_v1beta_generated_SearchTuningService_ListCustomModels_sync", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11010,44 +11928,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_schema_service_update_schema_sync.py" + "title": "discoveryengine_v1beta_generated_search_tuning_service_list_custom_models_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceAsyncClient", + "shortName": "SearchTuningServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient.search", + "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceAsyncClient.train_custom_model", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchService.Search", + "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService.TrainCustomModel", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchService", - "shortName": "SearchService" + "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService", + "shortName": "SearchTuningService" }, - "shortName": "Search" + "shortName": "TrainCustomModel" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" + "type": "google.cloud.discoveryengine_v1beta.types.TrainCustomModelRequest" }, { "name": "retry", @@ -11062,22 +11980,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "train_custom_model" }, - "description": "Sample for Search", - "file": "discoveryengine_v1beta_generated_search_service_search_async.py", + "description": "Sample for TrainCustomModel", + "file": "discoveryengine_v1beta_generated_search_tuning_service_train_custom_model_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SearchService_Search_async", + "regionTag": "discoveryengine_v1beta_generated_SearchTuningService_TrainCustomModel_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -11092,38 +12010,38 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_search_service_search_async.py" + "title": "discoveryengine_v1beta_generated_search_tuning_service_train_custom_model_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient", - "shortName": "SearchServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceClient", + "shortName": "SearchTuningServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient.search", + "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceClient.train_custom_model", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchService.Search", + "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService.TrainCustomModel", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchService", - "shortName": "SearchService" + "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService", + "shortName": "SearchTuningService" }, - "shortName": "Search" + "shortName": "TrainCustomModel" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" + "type": "google.cloud.discoveryengine_v1beta.types.TrainCustomModelRequest" }, { "name": "retry", @@ -11138,22 +12056,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchPager", - "shortName": "search" + "resultType": "google.api_core.operation.Operation", + "shortName": "train_custom_model" }, - "description": "Sample for Search", - "file": "discoveryengine_v1beta_generated_search_service_search_sync.py", + "description": "Sample for TrainCustomModel", + "file": "discoveryengine_v1beta_generated_search_tuning_service_train_custom_model_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SearchService_Search_sync", + "regionTag": "discoveryengine_v1beta_generated_SearchTuningService_TrainCustomModel_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -11168,39 +12086,43 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_search_service_search_sync.py" + "title": "discoveryengine_v1beta_generated_search_tuning_service_train_custom_model_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceAsyncClient", - "shortName": "SearchTuningServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceAsyncClient.list_custom_models", + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient.get_serving_config", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService.ListCustomModels", + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.GetServingConfig", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService", - "shortName": "SearchTuningService" + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", + "shortName": "ServingConfigService" }, - "shortName": "ListCustomModels" + "shortName": "GetServingConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListCustomModelsRequest" + "type": "google.cloud.discoveryengine_v1beta.types.GetServingConfigRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -11215,14 +12137,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.ListCustomModelsResponse", - "shortName": "list_custom_models" + "resultType": "google.cloud.discoveryengine_v1beta.types.ServingConfig", + "shortName": "get_serving_config" }, - "description": "Sample for ListCustomModels", - "file": "discoveryengine_v1beta_generated_search_tuning_service_list_custom_models_async.py", + "description": "Sample for GetServingConfig", + "file": "discoveryengine_v1beta_generated_serving_config_service_get_serving_config_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SearchTuningService_ListCustomModels_async", + "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_GetServingConfig_async", "segments": [ { "end": 51, @@ -11255,28 +12177,32 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_search_tuning_service_list_custom_models_async.py" + "title": "discoveryengine_v1beta_generated_serving_config_service_get_serving_config_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceClient", - "shortName": "SearchTuningServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceClient.list_custom_models", + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient.get_serving_config", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService.ListCustomModels", + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.GetServingConfig", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService", - "shortName": "SearchTuningService" + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", + "shortName": "ServingConfigService" }, - "shortName": "ListCustomModels" + "shortName": "GetServingConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListCustomModelsRequest" + "type": "google.cloud.discoveryengine_v1beta.types.GetServingConfigRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -11291,14 +12217,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.ListCustomModelsResponse", - "shortName": "list_custom_models" + "resultType": "google.cloud.discoveryengine_v1beta.types.ServingConfig", + "shortName": "get_serving_config" }, - "description": "Sample for ListCustomModels", - "file": "discoveryengine_v1beta_generated_search_tuning_service_list_custom_models_sync.py", + "description": "Sample for GetServingConfig", + "file": "discoveryengine_v1beta_generated_serving_config_service_get_serving_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SearchTuningService_ListCustomModels_sync", + "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_GetServingConfig_sync", "segments": [ { "end": 51, @@ -11331,29 +12257,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_search_tuning_service_list_custom_models_sync.py" + "title": "discoveryengine_v1beta_generated_serving_config_service_get_serving_config_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceAsyncClient", - "shortName": "SearchTuningServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient", + "shortName": "ServingConfigServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceAsyncClient.train_custom_model", + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient.list_serving_configs", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService.TrainCustomModel", + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.ListServingConfigs", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService", - "shortName": "SearchTuningService" + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", + "shortName": "ServingConfigService" }, - "shortName": "TrainCustomModel" + "shortName": "ListServingConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.TrainCustomModelRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListServingConfigsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -11368,22 +12298,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "train_custom_model" + "resultType": "google.cloud.discoveryengine_v1beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager", + "shortName": "list_serving_configs" }, - "description": "Sample for TrainCustomModel", - "file": "discoveryengine_v1beta_generated_search_tuning_service_train_custom_model_async.py", + "description": "Sample for ListServingConfigs", + "file": "discoveryengine_v1beta_generated_serving_config_service_list_serving_configs_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SearchTuningService_TrainCustomModel_async", + "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_ListServingConfigs_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -11398,38 +12328,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_search_tuning_service_train_custom_model_async.py" + "title": "discoveryengine_v1beta_generated_serving_config_service_list_serving_configs_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceClient", - "shortName": "SearchTuningServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient", + "shortName": "ServingConfigServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SearchTuningServiceClient.train_custom_model", + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient.list_serving_configs", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService.TrainCustomModel", + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.ListServingConfigs", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchTuningService", - "shortName": "SearchTuningService" + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", + "shortName": "ServingConfigService" }, - "shortName": "TrainCustomModel" + "shortName": "ListServingConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.TrainCustomModelRequest" + "type": "google.cloud.discoveryengine_v1beta.types.ListServingConfigsRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -11444,22 +12378,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "train_custom_model" + "resultType": "google.cloud.discoveryengine_v1beta.services.serving_config_service.pagers.ListServingConfigsPager", + "shortName": "list_serving_configs" }, - "description": "Sample for TrainCustomModel", - "file": "discoveryengine_v1beta_generated_search_tuning_service_train_custom_model_sync.py", + "description": "Sample for ListServingConfigs", + "file": "discoveryengine_v1beta_generated_serving_config_service_list_serving_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SearchTuningService_TrainCustomModel_sync", + "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_ListServingConfigs_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -11474,17 +12408,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_search_tuning_service_train_custom_model_sync.py" + "title": "discoveryengine_v1beta_generated_serving_config_service_list_serving_configs_sync.py" }, { "canonical": true, @@ -11494,23 +12428,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient", "shortName": "ServingConfigServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient.get_serving_config", + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient.update_serving_config", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.GetServingConfig", + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.UpdateServingConfig", "service": { "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", "shortName": "ServingConfigService" }, - "shortName": "GetServingConfig" + "shortName": "UpdateServingConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetServingConfigRequest" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateServingConfigRequest" }, { - "name": "name", - "type": "str" + "name": "serving_config", + "type": "google.cloud.discoveryengine_v1beta.types.ServingConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -11526,21 +12464,21 @@ } ], "resultType": "google.cloud.discoveryengine_v1beta.types.ServingConfig", - "shortName": "get_serving_config" + "shortName": "update_serving_config" }, - "description": "Sample for GetServingConfig", - "file": "discoveryengine_v1beta_generated_serving_config_service_get_serving_config_async.py", + "description": "Sample for UpdateServingConfig", + "file": "discoveryengine_v1beta_generated_serving_config_service_update_serving_config_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_GetServingConfig_async", + "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_UpdateServingConfig_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11550,22 +12488,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_serving_config_service_get_serving_config_async.py" + "title": "discoveryengine_v1beta_generated_serving_config_service_update_serving_config_async.py" }, { "canonical": true, @@ -11574,23 +12512,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient", "shortName": "ServingConfigServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient.get_serving_config", + "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient.update_serving_config", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.GetServingConfig", + "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.UpdateServingConfig", "service": { "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", "shortName": "ServingConfigService" }, - "shortName": "GetServingConfig" + "shortName": "UpdateServingConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetServingConfigRequest" + "type": "google.cloud.discoveryengine_v1beta.types.UpdateServingConfigRequest" }, { - "name": "name", - "type": "str" + "name": "serving_config", + "type": "google.cloud.discoveryengine_v1beta.types.ServingConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -11606,21 +12548,21 @@ } ], "resultType": "google.cloud.discoveryengine_v1beta.types.ServingConfig", - "shortName": "get_serving_config" + "shortName": "update_serving_config" }, - "description": "Sample for GetServingConfig", - "file": "discoveryengine_v1beta_generated_serving_config_service_get_serving_config_sync.py", + "description": "Sample for UpdateServingConfig", + "file": "discoveryengine_v1beta_generated_serving_config_service_update_serving_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_GetServingConfig_sync", + "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_UpdateServingConfig_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11630,48 +12572,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_serving_config_service_get_serving_config_sync.py" + "title": "discoveryengine_v1beta_generated_serving_config_service_update_serving_config_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient", + "shortName": "SiteSearchEngineServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient.list_serving_configs", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.batch_create_target_sites", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.ListServingConfigs", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", - "shortName": "ServingConfigService" + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" }, - "shortName": "ListServingConfigs" + "shortName": "BatchCreateTargetSites" }, "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListServingConfigsRequest" - }, - { - "name": "parent", - "type": "str" + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.BatchCreateTargetSitesRequest" }, { "name": "retry", @@ -11686,22 +12624,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.serving_config_service.pagers.ListServingConfigsAsyncPager", - "shortName": "list_serving_configs" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "batch_create_target_sites" }, - "description": "Sample for ListServingConfigs", - "file": "discoveryengine_v1beta_generated_serving_config_service_list_serving_configs_async.py", + "description": "Sample for BatchCreateTargetSites", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_batch_create_target_sites_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_ListServingConfigs_async", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_BatchCreateTargetSites_async", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -11711,47 +12649,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_serving_config_service_list_serving_configs_async.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_batch_create_target_sites_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient", + "shortName": "SiteSearchEngineServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient.list_serving_configs", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.batch_create_target_sites", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.ListServingConfigs", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", - "shortName": "ServingConfigService" + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" }, - "shortName": "ListServingConfigs" + "shortName": "BatchCreateTargetSites" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListServingConfigsRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.discoveryengine_v1beta.types.BatchCreateTargetSitesRequest" }, { "name": "retry", @@ -11766,22 +12700,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.services.serving_config_service.pagers.ListServingConfigsPager", - "shortName": "list_serving_configs" + "resultType": "google.api_core.operation.Operation", + "shortName": "batch_create_target_sites" }, - "description": "Sample for ListServingConfigs", - "file": "discoveryengine_v1beta_generated_serving_config_service_list_serving_configs_sync.py", + "description": "Sample for BatchCreateTargetSites", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_batch_create_target_sites_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_ListServingConfigs_sync", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_BatchCreateTargetSites_sync", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -11791,52 +12725,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_serving_config_service_list_serving_configs_sync.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_batch_create_target_sites_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient", - "shortName": "ServingConfigServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient", + "shortName": "SiteSearchEngineServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceAsyncClient.update_serving_config", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.batch_verify_target_sites", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.UpdateServingConfig", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", - "shortName": "ServingConfigService" + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" }, - "shortName": "UpdateServingConfig" + "shortName": "BatchVerifyTargetSites" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.discoveryengine_v1beta.types.ServingConfig" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "type": "google.cloud.discoveryengine_v1beta.types.BatchVerifyTargetSitesRequest" }, { "name": "retry", @@ -11851,22 +12777,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.ServingConfig", - "shortName": "update_serving_config" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "batch_verify_target_sites" }, - "description": "Sample for UpdateServingConfig", - "file": "discoveryengine_v1beta_generated_serving_config_service_update_serving_config_async.py", + "description": "Sample for BatchVerifyTargetSites", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_batch_verify_target_sites_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_UpdateServingConfig_async", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_BatchVerifyTargetSites_async", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -11876,51 +12802,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_serving_config_service_update_serving_config_async.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_batch_verify_target_sites_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient", - "shortName": "ServingConfigServiceClient" + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient", + "shortName": "SiteSearchEngineServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.ServingConfigServiceClient.update_serving_config", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.batch_verify_target_sites", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService.UpdateServingConfig", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites", "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ServingConfigService", - "shortName": "ServingConfigService" + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" }, - "shortName": "UpdateServingConfig" + "shortName": "BatchVerifyTargetSites" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateServingConfigRequest" - }, - { - "name": "serving_config", - "type": "google.cloud.discoveryengine_v1beta.types.ServingConfig" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "type": "google.cloud.discoveryengine_v1beta.types.BatchVerifyTargetSitesRequest" }, { "name": "retry", @@ -11935,22 +12853,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1beta.types.ServingConfig", - "shortName": "update_serving_config" + "resultType": "google.api_core.operation.Operation", + "shortName": "batch_verify_target_sites" }, - "description": "Sample for UpdateServingConfig", - "file": "discoveryengine_v1beta_generated_serving_config_service_update_serving_config_sync.py", + "description": "Sample for BatchVerifyTargetSites", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_batch_verify_target_sites_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ServingConfigService_UpdateServingConfig_sync", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_BatchVerifyTargetSites_sync", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -11960,22 +12878,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_serving_config_service_update_serving_config_sync.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_batch_verify_target_sites_sync.py" }, { "canonical": true, @@ -11985,19 +12903,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient", "shortName": "SiteSearchEngineServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.batch_create_target_sites", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.create_sitemap", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "BatchCreateTargetSites" + "shortName": "CreateSitemap" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.BatchCreateTargetSitesRequest" + "type": "google.cloud.discoveryengine_v1beta.types.CreateSitemapRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sitemap", + "type": "google.cloud.discoveryengine_v1beta.types.Sitemap" }, { "name": "retry", @@ -12013,21 +12939,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_create_target_sites" + "shortName": "create_sitemap" }, - "description": "Sample for BatchCreateTargetSites", - "file": "discoveryengine_v1beta_generated_site_search_engine_service_batch_create_target_sites_async.py", + "description": "Sample for CreateSitemap", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_BatchCreateTargetSites_async", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_CreateSitemap_async", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -12037,22 +12963,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_site_search_engine_service_batch_create_target_sites_async.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_async.py" }, { "canonical": true, @@ -12061,19 +12987,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient", "shortName": "SiteSearchEngineServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.batch_create_target_sites", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.create_sitemap", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchCreateTargetSites", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateSitemap", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "BatchCreateTargetSites" + "shortName": "CreateSitemap" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.BatchCreateTargetSitesRequest" + "type": "google.cloud.discoveryengine_v1beta.types.CreateSitemapRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sitemap", + "type": "google.cloud.discoveryengine_v1beta.types.Sitemap" }, { "name": "retry", @@ -12089,21 +13023,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "batch_create_target_sites" + "shortName": "create_sitemap" }, - "description": "Sample for BatchCreateTargetSites", - "file": "discoveryengine_v1beta_generated_site_search_engine_service_batch_create_target_sites_sync.py", + "description": "Sample for CreateSitemap", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_BatchCreateTargetSites_sync", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_CreateSitemap_sync", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -12113,22 +13047,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_site_search_engine_service_batch_create_target_sites_sync.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_create_sitemap_sync.py" }, { "canonical": true, @@ -12138,19 +13072,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient", "shortName": "SiteSearchEngineServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.batch_verify_target_sites", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.create_target_site", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "BatchVerifyTargetSites" + "shortName": "CreateTargetSite" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.BatchVerifyTargetSitesRequest" + "type": "google.cloud.discoveryengine_v1beta.types.CreateTargetSiteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "target_site", + "type": "google.cloud.discoveryengine_v1beta.types.TargetSite" }, { "name": "retry", @@ -12166,21 +13108,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_verify_target_sites" + "shortName": "create_target_site" }, - "description": "Sample for BatchVerifyTargetSites", - "file": "discoveryengine_v1beta_generated_site_search_engine_service_batch_verify_target_sites_async.py", + "description": "Sample for CreateTargetSite", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_create_target_site_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_BatchVerifyTargetSites_async", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_CreateTargetSite_async", "segments": [ { - "end": 55, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 59, "start": 27, "type": "SHORT" }, @@ -12190,22 +13132,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_site_search_engine_service_batch_verify_target_sites_async.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_create_target_site_async.py" }, { "canonical": true, @@ -12214,19 +13156,27 @@ "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient", "shortName": "SiteSearchEngineServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.batch_verify_target_sites", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.create_target_site", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.BatchVerifyTargetSites", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "BatchVerifyTargetSites" + "shortName": "CreateTargetSite" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.BatchVerifyTargetSitesRequest" + "type": "google.cloud.discoveryengine_v1beta.types.CreateTargetSiteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "target_site", + "type": "google.cloud.discoveryengine_v1beta.types.TargetSite" }, { "name": "retry", @@ -12242,21 +13192,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "batch_verify_target_sites" + "shortName": "create_target_site" }, - "description": "Sample for BatchVerifyTargetSites", - "file": "discoveryengine_v1beta_generated_site_search_engine_service_batch_verify_target_sites_sync.py", + "description": "Sample for CreateTargetSite", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_create_target_site_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_BatchVerifyTargetSites_sync", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_CreateTargetSite_sync", "segments": [ { - "end": 55, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 59, "start": 27, "type": "SHORT" }, @@ -12266,22 +13216,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_site_search_engine_service_batch_verify_target_sites_sync.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_create_target_site_sync.py" }, { "canonical": true, @@ -12291,28 +13241,24 @@ "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient", "shortName": "SiteSearchEngineServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.create_target_site", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.delete_sitemap", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "CreateTargetSite" + "shortName": "DeleteSitemap" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateTargetSiteRequest" + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSitemapRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "target_site", - "type": "google.cloud.discoveryengine_v1beta.types.TargetSite" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -12327,21 +13273,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_target_site" + "shortName": "delete_sitemap" }, - "description": "Sample for CreateTargetSite", - "file": "discoveryengine_v1beta_generated_site_search_engine_service_create_target_site_async.py", + "description": "Sample for DeleteSitemap", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_CreateTargetSite_async", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_DeleteSitemap_async", "segments": [ { - "end": 59, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 55, "start": 27, "type": "SHORT" }, @@ -12351,22 +13297,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_site_search_engine_service_create_target_site_async.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_async.py" }, { "canonical": true, @@ -12375,28 +13321,24 @@ "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient", "shortName": "SiteSearchEngineServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.create_target_site", + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.delete_sitemap", "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.CreateTargetSite", + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.DeleteSitemap", "service": { "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "CreateTargetSite" + "shortName": "DeleteSitemap" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateTargetSiteRequest" + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSitemapRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "target_site", - "type": "google.cloud.discoveryengine_v1beta.types.TargetSite" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -12411,21 +13353,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_target_site" + "shortName": "delete_sitemap" }, - "description": "Sample for CreateTargetSite", - "file": "discoveryengine_v1beta_generated_site_search_engine_service_create_target_site_sync.py", + "description": "Sample for DeleteSitemap", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_CreateTargetSite_sync", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_DeleteSitemap_sync", "segments": [ { - "end": 59, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 55, "start": 27, "type": "SHORT" }, @@ -12435,22 +13377,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1beta_generated_site_search_engine_service_create_target_site_sync.py" + "title": "discoveryengine_v1beta_generated_site_search_engine_service_delete_sitemap_sync.py" }, { "canonical": true, @@ -13072,6 +14014,167 @@ ], "title": "discoveryengine_v1beta_generated_site_search_engine_service_fetch_domain_verification_status_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient", + "shortName": "SiteSearchEngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceAsyncClient.fetch_sitemaps", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" + }, + "shortName": "FetchSitemaps" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.FetchSitemapsResponse", + "shortName": "fetch_sitemaps" + }, + "description": "Sample for FetchSitemaps", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_FetchSitemaps_async", + "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": "discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient", + "shortName": "SiteSearchEngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SiteSearchEngineServiceClient.fetch_sitemaps", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService.FetchSitemaps", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" + }, + "shortName": "FetchSitemaps" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.FetchSitemapsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.FetchSitemapsResponse", + "shortName": "fetch_sitemaps" + }, + "description": "Sample for FetchSitemaps", + "file": "discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SiteSearchEngineService_FetchSitemaps_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": "discoveryengine_v1beta_generated_site_search_engine_service_fetch_sitemaps_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1beta_keywords.py b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1beta_keywords.py index f2f74d58b3d5..4a6ebb02aaf6 100644 --- a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1beta_keywords.py +++ b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1beta_keywords.py @@ -39,7 +39,8 @@ def partition( class discoveryengineCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'answer_query': ('serving_config', 'query', 'session', 'safety_spec', 'related_questions_spec', 'answer_generation_spec', 'search_spec', 'query_understanding_spec', 'asynchronous_mode', 'user_pseudo_id', 'user_labels', ), + 'advanced_complete_query': ('completion_config', 'query', 'query_model', 'user_pseudo_id', 'user_info', 'include_tail_suggestions', 'boost_spec', 'suggestion_types', ), + 'answer_query': ('serving_config', 'query', 'session', 'safety_spec', 'related_questions_spec', 'grounding_spec', 'answer_generation_spec', 'search_spec', 'query_understanding_spec', 'asynchronous_mode', 'user_pseudo_id', 'user_labels', ), 'batch_create_target_sites': ('parent', 'requests', ), 'batch_get_documents_metadata': ('parent', 'matcher', ), 'batch_verify_target_sites': ('parent', ), @@ -57,6 +58,7 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'create_sample_query_set': ('parent', 'sample_query_set', 'sample_query_set_id', ), 'create_schema': ('parent', 'schema', 'schema_id', ), 'create_session': ('parent', 'session', ), + 'create_sitemap': ('parent', 'sitemap', ), 'create_target_site': ('parent', 'target_site', ), 'delete_control': ('name', ), 'delete_conversation': ('name', ), @@ -67,10 +69,13 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'delete_sample_query_set': ('name', ), 'delete_schema': ('name', ), 'delete_session': ('name', ), + 'delete_sitemap': ('name', ), 'delete_target_site': ('name', ), 'disable_advanced_site_search': ('site_search_engine', ), 'enable_advanced_site_search': ('site_search_engine', ), 'fetch_domain_verification_status': ('site_search_engine', 'page_size', 'page_token', ), + 'fetch_sitemaps': ('parent', 'matcher', ), + 'generate_grounded_content': ('location', 'system_instruction', 'contents', 'generation_spec', 'grounding_spec', 'user_labels', ), 'get_answer': ('name', ), 'get_control': ('name', ), 'get_conversation': ('name', ), @@ -112,9 +117,11 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'purge_user_events': ('parent', 'filter', 'force', ), 'rank': ('ranking_config', 'records', 'model', 'top_n', 'query', 'ignore_record_details_in_response', 'user_labels', ), 'recommend': ('serving_config', 'user_event', 'page_size', 'filter', 'validate_only', 'params', 'user_labels', ), - 'recrawl_uris': ('site_search_engine', 'uris', ), + 'recrawl_uris': ('site_search_engine', 'uris', 'site_credential', ), 'resume_engine': ('name', ), - 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'data_store_specs', 'filter', 'canonical_filter', 'order_by', 'user_info', 'language_code', 'region_code', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', 'natural_language_query_understanding_spec', 'search_as_you_type_spec', 'session', 'session_spec', 'relevance_threshold', ), + 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'one_box_page_size', 'data_store_specs', 'filter', 'canonical_filter', 'order_by', 'user_info', 'language_code', 'region_code', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', 'natural_language_query_understanding_spec', 'search_as_you_type_spec', 'session', 'session_spec', 'relevance_threshold', 'personalization_spec', ), + 'search_lite': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'one_box_page_size', 'data_store_specs', 'filter', 'canonical_filter', 'order_by', 'user_info', 'language_code', 'region_code', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', 'natural_language_query_understanding_spec', 'search_as_you_type_spec', 'session', 'session_spec', 'relevance_threshold', 'personalization_spec', ), + 'stream_generate_grounded_content': ('location', 'system_instruction', 'contents', 'generation_spec', 'grounding_spec', 'user_labels', ), 'train_custom_model': ('data_store', 'gcs_training_input', 'model_type', 'error_config', 'model_id', ), 'tune_engine': ('name', ), 'update_control': ('control', 'update_mask', ), diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py index ff8a2af86963..d17a955d9d00 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py @@ -70,6 +70,7 @@ transports, ) from google.cloud.discoveryengine_v1beta.types import ( + common, completion, completion_service, import_config, @@ -1442,6 +1443,269 @@ async def test_complete_query_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + completion_service.AdvancedCompleteQueryRequest, + dict, + ], +) +def test_advanced_complete_query(request_type, transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.advanced_complete_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.AdvancedCompleteQueryResponse( + tail_match_triggered=True, + ) + response = client.advanced_complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = completion_service.AdvancedCompleteQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.AdvancedCompleteQueryResponse) + assert response.tail_match_triggered is True + + +def test_advanced_complete_query_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = completion_service.AdvancedCompleteQueryRequest( + completion_config="completion_config_value", + query="query_value", + query_model="query_model_value", + user_pseudo_id="user_pseudo_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.advanced_complete_query), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.advanced_complete_query(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.AdvancedCompleteQueryRequest( + completion_config="completion_config_value", + query="query_value", + query_model="query_model_value", + user_pseudo_id="user_pseudo_id_value", + ) + + +def test_advanced_complete_query_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 = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.advanced_complete_query + 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.advanced_complete_query + ] = mock_rpc + request = {} + client.advanced_complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.advanced_complete_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_advanced_complete_query_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.advanced_complete_query + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.advanced_complete_query + ] = mock_rpc + + request = {} + await client.advanced_complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.advanced_complete_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_advanced_complete_query_async( + transport: str = "grpc_asyncio", + request_type=completion_service.AdvancedCompleteQueryRequest, +): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.advanced_complete_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + completion_service.AdvancedCompleteQueryResponse( + tail_match_triggered=True, + ) + ) + response = await client.advanced_complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = completion_service.AdvancedCompleteQueryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.AdvancedCompleteQueryResponse) + assert response.tail_match_triggered is True + + +@pytest.mark.asyncio +async def test_advanced_complete_query_async_from_dict(): + await test_advanced_complete_query_async(request_type=dict) + + +def test_advanced_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.AdvancedCompleteQueryRequest() + + request.completion_config = "completion_config_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.advanced_complete_query), "__call__" + ) as call: + call.return_value = completion_service.AdvancedCompleteQueryResponse() + client.advanced_complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "completion_config=completion_config_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_advanced_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.AdvancedCompleteQueryRequest() + + request.completion_config = "completion_config_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.advanced_complete_query), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + completion_service.AdvancedCompleteQueryResponse() + ) + await client.advanced_complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "completion_config=completion_config_value", + ) in kw["metadata"] + + @pytest.mark.parametrize( "request_type", [ @@ -2510,25 +2774,186 @@ def test_complete_query_rest_use_cached_wrapped_rpc(): client._transport._wrapped_methods[client._transport.complete_query] = mock_rpc request = {} - client.complete_query(request) + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.complete_query(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_complete_query_rest_required_fields( + request_type=completion_service.CompleteQueryRequest, +): + transport_class = transports.CompletionServiceRestTransport + + request_init = {} + request_init["data_store"] = "" + request_init["query"] = "" + 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 + assert "query" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).complete_query._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "query" in jsonified_request + assert jsonified_request["query"] == request_init["query"] + + jsonified_request["dataStore"] = "data_store_value" + jsonified_request["query"] = "query_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).complete_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "include_tail_suggestions", + "query", + "query_model", + "user_pseudo_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "dataStore" in jsonified_request + assert jsonified_request["dataStore"] == "data_store_value" + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" + + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = completion_service.CompleteQueryResponse() + # 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 = completion_service.CompleteQueryResponse.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 + + response = client.complete_query(request) + + expected_params = [ + ( + "query", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_complete_query_rest_unset_required_fields(): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.complete_query._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "includeTailSuggestions", + "query", + "queryModel", + "userPseudoId", + ) + ) + & set( + ( + "dataStore", + "query", + ) + ) + ) + + +def test_advanced_complete_query_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 = CompletionServiceClient( + 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.advanced_complete_query + 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.advanced_complete_query + ] = mock_rpc + + request = {} + client.advanced_complete_query(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.complete_query(request) + client.advanced_complete_query(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_complete_query_rest_required_fields( - request_type=completion_service.CompleteQueryRequest, +def test_advanced_complete_query_rest_required_fields( + request_type=completion_service.AdvancedCompleteQueryRequest, ): transport_class = transports.CompletionServiceRestTransport request_init = {} - request_init["data_store"] = "" + request_init["completion_config"] = "" request_init["query"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) @@ -2537,37 +2962,25 @@ def test_complete_query_rest_required_fields( ) # verify fields with default values are dropped - assert "query" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).complete_query._get_unset_required_fields(jsonified_request) + ).advanced_complete_query._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "query" in jsonified_request - assert jsonified_request["query"] == request_init["query"] - jsonified_request["dataStore"] = "data_store_value" + jsonified_request["completionConfig"] = "completion_config_value" jsonified_request["query"] = "query_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).complete_query._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "include_tail_suggestions", - "query", - "query_model", - "user_pseudo_id", - ) - ) + ).advanced_complete_query._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "dataStore" in jsonified_request - assert jsonified_request["dataStore"] == "data_store_value" + assert "completionConfig" in jsonified_request + assert jsonified_request["completionConfig"] == "completion_config_value" assert "query" in jsonified_request assert jsonified_request["query"] == "query_value" @@ -2578,7 +2991,7 @@ def test_complete_query_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = completion_service.CompleteQueryResponse() + return_value = completion_service.AdvancedCompleteQueryResponse() # 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 @@ -2590,52 +3003,42 @@ def test_complete_query_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "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 = completion_service.CompleteQueryResponse.pb(return_value) + return_value = completion_service.AdvancedCompleteQueryResponse.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 - response = client.complete_query(request) + response = client.advanced_complete_query(request) - expected_params = [ - ( - "query", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_complete_query_rest_unset_required_fields(): +def test_advanced_complete_query_rest_unset_required_fields(): transport = transports.CompletionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.complete_query._get_unset_required_fields({}) + unset_fields = transport.advanced_complete_query._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "includeTailSuggestions", - "query", - "queryModel", - "userPseudoId", - ) - ) + set(()) & set( ( - "dataStore", + "completionConfig", "query", ) ) @@ -3279,6 +3682,29 @@ def test_complete_query_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_advanced_complete_query_empty_call_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.advanced_complete_query), "__call__" + ) as call: + call.return_value = completion_service.AdvancedCompleteQueryResponse() + client.advanced_complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.AdvancedCompleteQueryRequest() + + 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_import_suggestion_deny_list_entries_empty_call_grpc(): @@ -3412,6 +3838,35 @@ async def test_complete_query_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_advanced_complete_query_empty_call_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.advanced_complete_query), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + completion_service.AdvancedCompleteQueryResponse( + tail_match_triggered=True, + ) + ) + await client.advanced_complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.AdvancedCompleteQueryRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -3652,6 +4107,131 @@ def test_complete_query_rest_interceptors(null_interceptor): post.assert_called_once() +def test_advanced_complete_query_rest_bad_request( + request_type=completion_service.AdvancedCompleteQueryRequest, +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "completion_config": "projects/sample1/locations/sample2/dataStores/sample3/completionConfig" + } + 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 + client.advanced_complete_query(request) + + +@pytest.mark.parametrize( + "request_type", + [ + completion_service.AdvancedCompleteQueryRequest, + dict, + ], +) +def test_advanced_complete_query_rest_call_success(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "completion_config": "projects/sample1/locations/sample2/dataStores/sample3/completionConfig" + } + 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 = completion_service.AdvancedCompleteQueryResponse( + tail_match_triggered=True, + ) + + # 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 = completion_service.AdvancedCompleteQueryResponse.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 + response = client.advanced_complete_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.AdvancedCompleteQueryResponse) + assert response.tail_match_triggered is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_advanced_complete_query_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(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.CompletionServiceRestInterceptor, "post_advanced_complete_query" + ) as post, mock.patch.object( + transports.CompletionServiceRestInterceptor, "pre_advanced_complete_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = completion_service.AdvancedCompleteQueryRequest.pb( + completion_service.AdvancedCompleteQueryRequest() + ) + 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 + return_value = completion_service.AdvancedCompleteQueryResponse.to_json( + completion_service.AdvancedCompleteQueryResponse() + ) + req.return_value.content = return_value + + request = completion_service.AdvancedCompleteQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = completion_service.AdvancedCompleteQueryResponse() + + client.advanced_complete_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + def test_import_suggestion_deny_list_entries_rest_bad_request( request_type=import_config.ImportSuggestionDenyListEntriesRequest, ): @@ -4355,6 +4935,28 @@ def test_complete_query_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_advanced_complete_query_empty_call_rest(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.advanced_complete_query), "__call__" + ) as call: + client.advanced_complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.AdvancedCompleteQueryRequest() + + 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_import_suggestion_deny_list_entries_empty_call_rest(): @@ -4494,6 +5096,7 @@ def test_completion_service_base_transport(): # raise NotImplementedError. methods = ( "complete_query", + "advanced_complete_query", "import_suggestion_deny_list_entries", "purge_suggestion_deny_list_entries", "import_completion_suggestions", @@ -4767,6 +5370,9 @@ def test_completion_service_client_transport_session_collision(transport_name): session1 = client1.transport.complete_query._session session2 = client2.transport.complete_query._session assert session1 != session2 + session1 = client1.transport.advanced_complete_query._session + session2 = client2.transport.advanced_complete_query._session + assert session1 != session2 session1 = client1.transport.import_suggestion_deny_list_entries._session session2 = client2.transport.import_suggestion_deny_list_entries._session assert session1 != session2 @@ -4941,25 +5547,53 @@ def test_completion_service_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_data_store_path(): +def test_completion_config_path(): project = "squid" location = "clam" data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format( + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/completionConfig".format( project=project, location=location, data_store=data_store, ) - actual = CompletionServiceClient.data_store_path(project, location, data_store) + actual = CompletionServiceClient.completion_config_path( + project, location, data_store + ) assert expected == actual -def test_parse_data_store_path(): +def test_parse_completion_config_path(): expected = { "project": "octopus", "location": "oyster", "data_store": "nudibranch", } + path = CompletionServiceClient.completion_config_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_completion_config_path(path) + assert expected == actual + + +def test_data_store_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format( + project=project, + location=location, + data_store=data_store, + ) + actual = CompletionServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "data_store": "abalone", + } path = CompletionServiceClient.data_store_path(**expected) # Check that the path construction is reversible. @@ -4967,8 +5601,42 @@ def test_parse_data_store_path(): assert expected == actual +def test_document_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + document = "oyster" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format( + project=project, + location=location, + data_store=data_store, + branch=branch, + document=document, + ) + actual = CompletionServiceClient.document_path( + project, location, data_store, branch, document + ) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "data_store": "mussel", + "branch": "winkle", + "document": "nautilus", + } + path = CompletionServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_document_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4978,7 +5646,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "abalone", } path = CompletionServiceClient.common_billing_account_path(**expected) @@ -4988,7 +5656,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -4998,7 +5666,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "clam", } path = CompletionServiceClient.common_folder_path(**expected) @@ -5008,7 +5676,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -5018,7 +5686,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "octopus", } path = CompletionServiceClient.common_organization_path(**expected) @@ -5028,7 +5696,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -5038,7 +5706,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "nudibranch", } path = CompletionServiceClient.common_project_path(**expected) @@ -5048,8 +5716,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -5060,8 +5728,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "winkle", + "location": "nautilus", } path = CompletionServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_control_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_control_service.py index a40663b031ed..80a4e5277cad 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_control_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_control_service.py @@ -4490,6 +4490,7 @@ def test_create_control_rest_call_success(request_type): "active_time_range": [ {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} ], + "query_regex": "query_regex_value", } ], } @@ -4830,6 +4831,7 @@ def test_update_control_rest_call_success(request_type): "active_time_range": [ {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} ], + "query_regex": "query_regex_value", } ], } diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_data_store_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_data_store_service.py index 84d96dd49944..43a099c3651b 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_data_store_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_data_store_service.py @@ -4587,6 +4587,21 @@ def test_create_data_store_rest_call_success(request_type): "language": "language_value", "region": "region_value", }, + "natural_language_query_understanding_config": {"mode": 1}, + "billing_estimation": { + "structured_data_size": 2152, + "unstructured_data_size": 2379, + "website_data_size": 1798, + "structured_data_update_time": {}, + "unstructured_data_update_time": {}, + "website_data_update_time": {}, + }, + "workspace_config": { + "type_": 1, + "dasher_customer_id": "dasher_customer_id_value", + "super_admin_service_account": "super_admin_service_account_value", + "super_admin_email_address": "super_admin_email_address_value", + }, "document_processing_config": { "name": "name_value", "chunking_config": { @@ -4613,6 +4628,7 @@ def test_create_data_store_rest_call_success(request_type): "json_schema": "json_schema_value", "name": "name_value", }, + "serving_config_data_store": {"disabled_for_serving": True}, } # 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 @@ -5179,6 +5195,21 @@ def test_update_data_store_rest_call_success(request_type): "language": "language_value", "region": "region_value", }, + "natural_language_query_understanding_config": {"mode": 1}, + "billing_estimation": { + "structured_data_size": 2152, + "unstructured_data_size": 2379, + "website_data_size": 1798, + "structured_data_update_time": {}, + "unstructured_data_update_time": {}, + "website_data_update_time": {}, + }, + "workspace_config": { + "type_": 1, + "dasher_customer_id": "dasher_customer_id_value", + "super_admin_service_account": "super_admin_service_account_value", + "super_admin_email_address": "super_admin_email_address_value", + }, "document_processing_config": { "name": "name_value", "chunking_config": { @@ -5205,6 +5236,7 @@ def test_update_data_store_rest_call_success(request_type): "json_schema": "json_schema_value", "name": "name_value", }, + "serving_config_data_store": {"disabled_for_serving": True}, } # 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-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py index d154fc633ccc..698c41b35e1d 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py @@ -8108,6 +8108,43 @@ def test_parse_document_path(): assert expected == actual +def test_fhir_resource_path(): + project = "cuttlefish" + location = "mussel" + dataset = "winkle" + fhir_store = "nautilus" + resource_type = "scallop" + fhir_resource_id = "abalone" + expected = "projects/{project}/locations/{location}/datasets/{dataset}/fhirStores/{fhir_store}/fhir/{resource_type}/{fhir_resource_id}".format( + project=project, + location=location, + dataset=dataset, + fhir_store=fhir_store, + resource_type=resource_type, + fhir_resource_id=fhir_resource_id, + ) + actual = DocumentServiceClient.fhir_resource_path( + project, location, dataset, fhir_store, resource_type, fhir_resource_id + ) + assert expected == actual + + +def test_parse_fhir_resource_path(): + expected = { + "project": "squid", + "location": "clam", + "dataset": "whelk", + "fhir_store": "octopus", + "resource_type": "oyster", + "fhir_resource_id": "nudibranch", + } + path = DocumentServiceClient.fhir_resource_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_fhir_resource_path(path) + assert expected == actual + + def test_fhir_store_path(): project = "cuttlefish" location = "mussel" diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_engine_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_engine_service.py index 4b18856c902b..3d820aec1f7f 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_engine_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_engine_service.py @@ -1891,6 +1891,7 @@ def test_update_engine(request_type, transport: str = "grpc"): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) response = client.update_engine(request) @@ -1907,6 +1908,7 @@ def test_update_engine(request_type, transport: str = "grpc"): assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True def test_update_engine_non_empty_request_with_auto_populated_field(): @@ -2033,6 +2035,7 @@ async def test_update_engine_async( data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) ) response = await client.update_engine(request) @@ -2050,6 +2053,7 @@ async def test_update_engine_async( assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True @pytest.mark.asyncio @@ -2268,6 +2272,7 @@ def test_get_engine(request_type, transport: str = "grpc"): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) response = client.get_engine(request) @@ -2284,6 +2289,7 @@ def test_get_engine(request_type, transport: str = "grpc"): assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True def test_get_engine_non_empty_request_with_auto_populated_field(): @@ -2412,6 +2418,7 @@ async def test_get_engine_async( data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) ) response = await client.get_engine(request) @@ -2429,6 +2436,7 @@ async def test_get_engine_async( assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True @pytest.mark.asyncio @@ -3122,6 +3130,7 @@ def test_pause_engine(request_type, transport: str = "grpc"): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) response = client.pause_engine(request) @@ -3138,6 +3147,7 @@ def test_pause_engine(request_type, transport: str = "grpc"): assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True def test_pause_engine_non_empty_request_with_auto_populated_field(): @@ -3268,6 +3278,7 @@ async def test_pause_engine_async( data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) ) response = await client.pause_engine(request) @@ -3285,6 +3296,7 @@ async def test_pause_engine_async( assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True @pytest.mark.asyncio @@ -3457,6 +3469,7 @@ def test_resume_engine(request_type, transport: str = "grpc"): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) response = client.resume_engine(request) @@ -3473,6 +3486,7 @@ def test_resume_engine(request_type, transport: str = "grpc"): assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True def test_resume_engine_non_empty_request_with_auto_populated_field(): @@ -3603,6 +3617,7 @@ async def test_resume_engine_async( data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) ) response = await client.resume_engine(request) @@ -3620,6 +3635,7 @@ async def test_resume_engine_async( assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True @pytest.mark.asyncio @@ -6009,6 +6025,7 @@ async def test_update_engine_empty_call_grpc_asyncio(): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) ) await client.update_engine(request=None) @@ -6040,6 +6057,7 @@ async def test_get_engine_empty_call_grpc_asyncio(): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) ) await client.get_engine(request=None) @@ -6098,6 +6116,7 @@ async def test_pause_engine_empty_call_grpc_asyncio(): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) ) await client.pause_engine(request=None) @@ -6129,6 +6148,7 @@ async def test_resume_engine_empty_call_grpc_asyncio(): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) ) await client.resume_engine(request=None) @@ -6231,6 +6251,7 @@ def test_create_engine_rest_call_success(request_type): "solution_type": 1, "industry_vertical": 1, "common_config": {"company_name": "company_name_value"}, + "disable_analytics": True, } # 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 @@ -6561,6 +6582,7 @@ def test_update_engine_rest_call_success(request_type): "solution_type": 1, "industry_vertical": 1, "common_config": {"company_name": "company_name_value"}, + "disable_analytics": True, } # 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 @@ -6640,6 +6662,7 @@ def get_message_fields(field): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) # Wrap the value into a proper Response obj @@ -6660,6 +6683,7 @@ def get_message_fields(field): assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6769,6 +6793,7 @@ def test_get_engine_rest_call_success(request_type): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) # Wrap the value into a proper Response obj @@ -6789,6 +6814,7 @@ def test_get_engine_rest_call_success(request_type): assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -7017,6 +7043,7 @@ def test_pause_engine_rest_call_success(request_type): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) # Wrap the value into a proper Response obj @@ -7037,6 +7064,7 @@ def test_pause_engine_rest_call_success(request_type): assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -7148,6 +7176,7 @@ def test_resume_engine_rest_call_success(request_type): data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, + disable_analytics=True, ) # Wrap the value into a proper Response obj @@ -7168,6 +7197,7 @@ def test_resume_engine_rest_call_success(request_type): assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.disable_analytics is True @pytest.mark.parametrize("null_interceptor", [True, False]) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_evaluation_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_evaluation_service.py index bc5c6cb7a26f..39ca5502a47d 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_evaluation_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_evaluation_service.py @@ -4467,7 +4467,10 @@ def test_create_evaluation_rest_call_success(request_type): "page_size": 951, "page_token": "page_token_value", "offset": 647, - "data_store_specs": [{"data_store": "data_store_value"}], + "one_box_page_size": 1792, + "data_store_specs": [ + {"data_store": "data_store_value", "filter": "filter_value"} + ], "filter": "filter_value", "canonical_filter": "canonical_filter_value", "order_by": "order_by_value", @@ -4544,6 +4547,7 @@ def test_create_evaluation_rest_call_success(request_type): "ignore_adversarial_query": True, "ignore_non_summary_seeking_query": True, "ignore_low_relevant_content": True, + "ignore_jail_breaking_query": True, "model_prompt_spec": {"preamble": "preamble_value"}, "language_code": "language_code_value", "model_spec": {"version": "version_value"}, @@ -4584,6 +4588,7 @@ def test_create_evaluation_rest_call_success(request_type): "search_result_persistence_count": 3328, }, "relevance_threshold": 1, + "personalization_spec": {"mode": 1}, }, "query_set_spec": {"sample_query_set": "sample_query_set_value"}, }, diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_grounded_generation_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_grounded_generation_service.py index 8e5e09d7481e..60d399a80d80 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_grounded_generation_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_grounded_generation_service.py @@ -1228,6 +1228,430 @@ def test_grounded_generation_service_client_create_channel_credentials_file( ) +@pytest.mark.parametrize( + "request_type", + [ + grounded_generation_service.GenerateGroundedContentRequest, + dict, + ], +) +def test_stream_generate_grounded_content(request_type, transport: str = "grpc"): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_generate_grounded_content), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iter( + [grounded_generation_service.GenerateGroundedContentResponse()] + ) + response = client.stream_generate_grounded_content(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance( + message, grounded_generation_service.GenerateGroundedContentResponse + ) + + +def test_stream_generate_grounded_content_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 = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.stream_generate_grounded_content + 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.stream_generate_grounded_content + ] = mock_rpc + request = [{}] + client.stream_generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stream_generate_grounded_content(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_stream_generate_grounded_content_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GroundedGenerationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.stream_generate_grounded_content + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.stream_generate_grounded_content + ] = mock_rpc + + request = [{}] + await client.stream_generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.stream_generate_grounded_content(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_stream_generate_grounded_content_async( + transport: str = "grpc_asyncio", + request_type=grounded_generation_service.GenerateGroundedContentRequest, +): + client = GroundedGenerationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stream_generate_grounded_content), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[grounded_generation_service.GenerateGroundedContentResponse()] + ) + response = await client.stream_generate_grounded_content(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance( + message, grounded_generation_service.GenerateGroundedContentResponse + ) + + +@pytest.mark.asyncio +async def test_stream_generate_grounded_content_async_from_dict(): + await test_stream_generate_grounded_content_async(request_type=dict) + + +@pytest.mark.parametrize( + "request_type", + [ + grounded_generation_service.GenerateGroundedContentRequest, + dict, + ], +) +def test_generate_grounded_content(request_type, transport: str = "grpc"): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_grounded_content), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + grounded_generation_service.GenerateGroundedContentResponse() + ) + response = client.generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = grounded_generation_service.GenerateGroundedContentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, grounded_generation_service.GenerateGroundedContentResponse + ) + + +def test_generate_grounded_content_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = grounded_generation_service.GenerateGroundedContentRequest( + location="location_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_grounded_content), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.generate_grounded_content(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == grounded_generation_service.GenerateGroundedContentRequest( + location="location_value", + ) + + +def test_generate_grounded_content_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 = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_grounded_content + 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.generate_grounded_content + ] = mock_rpc + request = {} + client.generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_grounded_content(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_grounded_content_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GroundedGenerationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.generate_grounded_content + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.generate_grounded_content + ] = mock_rpc + + request = {} + await client.generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_grounded_content(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_grounded_content_async( + transport: str = "grpc_asyncio", + request_type=grounded_generation_service.GenerateGroundedContentRequest, +): + client = GroundedGenerationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_grounded_content), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grounded_generation_service.GenerateGroundedContentResponse() + ) + response = await client.generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = grounded_generation_service.GenerateGroundedContentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, grounded_generation_service.GenerateGroundedContentResponse + ) + + +@pytest.mark.asyncio +async def test_generate_grounded_content_async_from_dict(): + await test_generate_grounded_content_async(request_type=dict) + + +def test_generate_grounded_content_field_headers(): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grounded_generation_service.GenerateGroundedContentRequest() + + request.location = "location_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_grounded_content), "__call__" + ) as call: + call.return_value = ( + grounded_generation_service.GenerateGroundedContentResponse() + ) + client.generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "location=location_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_generate_grounded_content_field_headers_async(): + client = GroundedGenerationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grounded_generation_service.GenerateGroundedContentRequest() + + request.location = "location_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_grounded_content), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grounded_generation_service.GenerateGroundedContentResponse() + ) + await client.generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "location=location_value", + ) in kw["metadata"] + + @pytest.mark.parametrize( "request_type", [ @@ -1416,60 +1840,200 @@ def test_check_grounding_field_headers(): credentials=ga_credentials.AnonymousCredentials(), ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grounded_generation_service.CheckGroundingRequest() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grounded_generation_service.CheckGroundingRequest() + + request.grounding_config = "grounding_config_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.check_grounding), "__call__") as call: + call.return_value = grounded_generation_service.CheckGroundingResponse() + client.check_grounding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "grounding_config=grounding_config_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_check_grounding_field_headers_async(): + client = GroundedGenerationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = grounded_generation_service.CheckGroundingRequest() + + request.grounding_config = "grounding_config_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.check_grounding), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grounded_generation_service.CheckGroundingResponse() + ) + await client.check_grounding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "grounding_config=grounding_config_value", + ) in kw["metadata"] + + +def test_stream_generate_grounded_content_rest_unimplemented(): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = grounded_generation_service.GenerateGroundedContentRequest() + requests = [request] + with pytest.raises(NotImplementedError): + client.stream_generate_grounded_content(requests) + + +def test_generate_grounded_content_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 = GroundedGenerationServiceClient( + 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.generate_grounded_content + 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.generate_grounded_content + ] = mock_rpc + + request = {} + client.generate_grounded_content(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_grounded_content(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_generate_grounded_content_rest_required_fields( + request_type=grounded_generation_service.GenerateGroundedContentRequest, +): + transport_class = transports.GroundedGenerationServiceRestTransport + + request_init = {} + request_init["location"] = "" + 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() + ).generate_grounded_content._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["location"] = "location_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_grounded_content._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "location" in jsonified_request + assert jsonified_request["location"] == "location_value" + + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = grounded_generation_service.GenerateGroundedContentResponse() + # 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 - request.grounding_config = "grounding_config_value" + # Convert return value to protobuf type + return_value = ( + grounded_generation_service.GenerateGroundedContentResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.check_grounding), "__call__") as call: - call.return_value = grounded_generation_service.CheckGroundingResponse() - client.check_grounding(request) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request + response = client.generate_grounded_content(request) - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "grounding_config=grounding_config_value", - ) in kw["metadata"] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -@pytest.mark.asyncio -async def test_check_grounding_field_headers_async(): - client = GroundedGenerationServiceAsyncClient( - credentials=async_anonymous_credentials(), +def test_generate_grounded_content_rest_unset_required_fields(): + transport = transports.GroundedGenerationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = grounded_generation_service.CheckGroundingRequest() - - request.grounding_config = "grounding_config_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.check_grounding), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - grounded_generation_service.CheckGroundingResponse() - ) - await client.check_grounding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "grounding_config=grounding_config_value", - ) in kw["metadata"] + unset_fields = transport.generate_grounded_content._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("location",))) def test_check_grounding_rest_use_cached_wrapped_rpc(): @@ -1700,6 +2264,31 @@ def test_initialize_client_w_grpc(): 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_generate_grounded_content_empty_call_grpc(): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_grounded_content), "__call__" + ) as call: + call.return_value = ( + grounded_generation_service.GenerateGroundedContentResponse() + ) + client.generate_grounded_content(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grounded_generation_service.GenerateGroundedContentRequest() + + 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_check_grounding_empty_call_grpc(): @@ -1735,6 +2324,33 @@ def test_initialize_client_w_grpc_asyncio(): 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. +@pytest.mark.asyncio +async def test_generate_grounded_content_empty_call_grpc_asyncio(): + client = GroundedGenerationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_grounded_content), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + grounded_generation_service.GenerateGroundedContentResponse() + ) + await client.generate_grounded_content(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grounded_generation_service.GenerateGroundedContentRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -1769,6 +2385,147 @@ def test_transport_kind_rest(): assert transport.kind == "rest" +def test_stream_generate_grounded_content_rest_error(): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.stream_generate_grounded_content({}) + assert ( + "Method StreamGenerateGroundedContent is not available over REST transport" + in str(not_implemented_error.value) + ) + + +def test_generate_grounded_content_rest_bad_request( + request_type=grounded_generation_service.GenerateGroundedContentRequest, +): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/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 + client.generate_grounded_content(request) + + +@pytest.mark.parametrize( + "request_type", + [ + grounded_generation_service.GenerateGroundedContentRequest, + dict, + ], +) +def test_generate_grounded_content_rest_call_success(request_type): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"location": "projects/sample1/locations/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 = grounded_generation_service.GenerateGroundedContentResponse() + + # 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 = grounded_generation_service.GenerateGroundedContentResponse.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 + response = client.generate_grounded_content(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, grounded_generation_service.GenerateGroundedContentResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_grounded_content_rest_interceptors(null_interceptor): + transport = transports.GroundedGenerationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GroundedGenerationServiceRestInterceptor(), + ) + client = GroundedGenerationServiceClient(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.GroundedGenerationServiceRestInterceptor, + "post_generate_grounded_content", + ) as post, mock.patch.object( + transports.GroundedGenerationServiceRestInterceptor, + "pre_generate_grounded_content", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = grounded_generation_service.GenerateGroundedContentRequest.pb( + grounded_generation_service.GenerateGroundedContentRequest() + ) + 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 + return_value = ( + grounded_generation_service.GenerateGroundedContentResponse.to_json( + grounded_generation_service.GenerateGroundedContentResponse() + ) + ) + req.return_value.content = return_value + + request = grounded_generation_service.GenerateGroundedContentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + grounded_generation_service.GenerateGroundedContentResponse() + ) + + client.generate_grounded_content( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + def test_check_grounding_rest_bad_request( request_type=grounded_generation_service.CheckGroundingRequest, ): @@ -2098,6 +2855,28 @@ def test_initialize_client_w_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_generate_grounded_content_empty_call_rest(): + client = GroundedGenerationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_grounded_content), "__call__" + ) as call: + client.generate_grounded_content(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = grounded_generation_service.GenerateGroundedContentRequest() + + 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_check_grounding_empty_call_rest(): @@ -2151,6 +2930,8 @@ def test_grounded_generation_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( + "stream_generate_grounded_content", + "generate_grounded_content", "check_grounding", "get_operation", "cancel_operation", @@ -2417,6 +3198,12 @@ def test_grounded_generation_service_client_transport_session_collision(transpor credentials=creds2, transport=transport_name, ) + session1 = client1.transport.stream_generate_grounded_content._session + session2 = client2.transport.stream_generate_grounded_content._session + assert session1 != session2 + session1 = client1.transport.generate_grounded_content._session + session2 = client2.transport.generate_grounded_content._session + assert session1 != session2 session1 = client1.transport.check_grounding._session session2 = client2.transport.check_grounding._session assert session1 != session2 @@ -2576,6 +3363,60 @@ def test_parse_grounding_config_path(): assert expected == actual +def test_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = GroundedGenerationServiceClient.location_path(project, location) + assert expected == actual + + +def test_parse_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = GroundedGenerationServiceClient.location_path(**expected) + + # Check that the path construction is reversible. + actual = GroundedGenerationServiceClient.parse_location_path(path) + assert expected == actual + + +def test_serving_config_path(): + project = "scallop" + location = "abalone" + data_store = "squid" + serving_config = "clam" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format( + project=project, + location=location, + data_store=data_store, + serving_config=serving_config, + ) + actual = GroundedGenerationServiceClient.serving_config_path( + project, location, data_store, serving_config + ) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "whelk", + "location": "octopus", + "data_store": "oyster", + "serving_config": "nudibranch", + } + path = GroundedGenerationServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = GroundedGenerationServiceClient.parse_serving_config_path(path) + assert expected == actual + + def test_common_billing_account_path(): billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py index a462fce08d95..f8d15fa7fbb9 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py @@ -1616,6 +1616,487 @@ async def test_search_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + search_service.SearchRequest, + dict, + ], +) +def test_search_lite(request_type, transport: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + attribution_token="attribution_token_value", + redirect_uri="redirect_uri_value", + next_page_token="next_page_token_value", + corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], + ) + response = client.search_lite(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = search_service.SearchRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchLitePager) + assert response.total_size == 1086 + assert response.attribution_token == "attribution_token_value" + assert response.redirect_uri == "redirect_uri_value" + assert response.next_page_token == "next_page_token_value" + assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] + + +def test_search_lite_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = search_service.SearchRequest( + serving_config="serving_config_value", + branch="branch_value", + query="query_value", + page_token="page_token_value", + filter="filter_value", + canonical_filter="canonical_filter_value", + order_by="order_by_value", + language_code="language_code_value", + region_code="region_code_value", + user_pseudo_id="user_pseudo_id_value", + ranking_expression="ranking_expression_value", + session="session_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.search_lite(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest( + serving_config="serving_config_value", + branch="branch_value", + query="query_value", + page_token="page_token_value", + filter="filter_value", + canonical_filter="canonical_filter_value", + order_by="order_by_value", + language_code="language_code_value", + region_code="region_code_value", + user_pseudo_id="user_pseudo_id_value", + ranking_expression="ranking_expression_value", + session="session_value", + ) + + +def test_search_lite_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 = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_lite 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.search_lite] = mock_rpc + request = {} + client.search_lite(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_lite(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_search_lite_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.search_lite + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.search_lite + ] = mock_rpc + + request = {} + await client.search_lite(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.search_lite(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_search_lite_async( + transport: str = "grpc_asyncio", request_type=search_service.SearchRequest +): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + search_service.SearchResponse( + total_size=1086, + attribution_token="attribution_token_value", + redirect_uri="redirect_uri_value", + next_page_token="next_page_token_value", + corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], + ) + ) + response = await client.search_lite(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = search_service.SearchRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchLiteAsyncPager) + assert response.total_size == 1086 + assert response.attribution_token == "attribution_token_value" + assert response.redirect_uri == "redirect_uri_value" + assert response.next_page_token == "next_page_token_value" + assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] + + +@pytest.mark.asyncio +async def test_search_lite_async_from_dict(): + await test_search_lite_async(request_type=dict) + + +def test_search_lite_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.serving_config = "serving_config_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + call.return_value = search_service.SearchResponse() + client.search_lite(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "serving_config=serving_config_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_search_lite_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.serving_config = "serving_config_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + search_service.SearchResponse() + ) + await client.search_lite(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "serving_config=serving_config_value", + ) in kw["metadata"] + + +def test_search_lite_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token="abc", + ), + search_service.SearchResponse( + results=[], + next_page_token="def", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token="ghi", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("serving_config", ""),)), + ) + pager = client.search_lite(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, search_service.SearchResponse.SearchResult) for i in results + ) + + +def test_search_lite_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token="abc", + ), + search_service.SearchResponse( + results=[], + next_page_token="def", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token="ghi", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search_lite(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_search_lite_async_pager(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_lite), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token="abc", + ), + search_service.SearchResponse( + results=[], + next_page_token="def", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token="ghi", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_lite( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, search_service.SearchResponse.SearchResult) for i in responses + ) + + +@pytest.mark.asyncio +async def test_search_lite_async_pages(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_lite), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token="abc", + ), + search_service.SearchResponse( + results=[], + next_page_token="def", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token="ghi", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_lite(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + def test_search_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1630,29 +2111,212 @@ def test_search_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.search in client._transport._wrapped_methods + assert client._transport.search 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.search] = mock_rpc + + request = {} + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search(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_search_rest_required_fields(request_type=search_service.SearchRequest): + transport_class = transports.SearchServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + 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() + ).search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["servingConfig"] = "serving_config_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == "serving_config_value" + + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = search_service.SearchResponse() + # 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 = search_service.SearchResponse.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 + + response = client.search(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_search_rest_unset_required_fields(): + transport = transports.SearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("servingConfig",))) + + +def test_search_rest_pager(transport: str = "rest"): + client = SearchServiceClient( + 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 = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token="abc", + ), + search_service.SearchResponse( + results=[], + next_page_token="def", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token="ghi", + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(search_service.SearchResponse.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 = { + "serving_config": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4" + } + + pager = client.search(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, search_service.SearchResponse.SearchResult) for i in results + ) + + pages = list(client.search(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_search_lite_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 = SearchServiceClient( + 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.search_lite 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.search] = mock_rpc + client._transport._wrapped_methods[client._transport.search_lite] = mock_rpc request = {} - client.search(request) + client.search_lite(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.search(request) + client.search_lite(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_search_rest_required_fields(request_type=search_service.SearchRequest): +def test_search_lite_rest_required_fields(request_type=search_service.SearchRequest): transport_class = transports.SearchServiceRestTransport request_init = {} @@ -1667,7 +2331,7 @@ def test_search_rest_required_fields(request_type=search_service.SearchRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).search._get_unset_required_fields(jsonified_request) + ).search_lite._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1676,7 +2340,7 @@ def test_search_rest_required_fields(request_type=search_service.SearchRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).search._get_unset_required_fields(jsonified_request) + ).search_lite._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -1718,23 +2382,23 @@ def test_search_rest_required_fields(request_type=search_service.SearchRequest): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.search(request) + response = client.search_lite(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_search_rest_unset_required_fields(): +def test_search_lite_rest_unset_required_fields(): transport = transports.SearchServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.search._get_unset_required_fields({}) + unset_fields = transport.search_lite._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("servingConfig",))) -def test_search_rest_pager(transport: str = "rest"): +def test_search_lite_rest_pager(transport: str = "rest"): client = SearchServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1786,7 +2450,7 @@ def test_search_rest_pager(transport: str = "rest"): "serving_config": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4" } - pager = client.search(request=sample_request) + pager = client.search_lite(request=sample_request) results = list(pager) assert len(results) == 6 @@ -1794,7 +2458,7 @@ def test_search_rest_pager(transport: str = "rest"): isinstance(i, search_service.SearchResponse.SearchResult) for i in results ) - pages = list(client.search(request=sample_request).pages) + pages = list(client.search_lite(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -1926,6 +2590,27 @@ def test_search_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_lite_empty_call_grpc(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + call.return_value = search_service.SearchResponse() + client.search_lite(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = SearchServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -1972,6 +2657,38 @@ async def test_search_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_lite_empty_call_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + search_service.SearchResponse( + total_size=1086, + attribution_token="attribution_token_value", + redirect_uri="redirect_uri_value", + next_page_token="next_page_token_value", + corrected_query="corrected_query_value", + applied_controls=["applied_controls_value"], + ) + ) + await client.search_lite(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = SearchServiceClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -2110,6 +2827,137 @@ def test_search_rest_interceptors(null_interceptor): post.assert_called_once() +def test_search_lite_rest_bad_request(request_type=search_service.SearchRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "serving_config": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 + client.search_lite(request) + + +@pytest.mark.parametrize( + "request_type", + [ + search_service.SearchRequest, + dict, + ], +) +def test_search_lite_rest_call_success(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "serving_config": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4" + } + 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 = search_service.SearchResponse( + total_size=1086, + attribution_token="attribution_token_value", + redirect_uri="redirect_uri_value", + next_page_token="next_page_token_value", + corrected_query="corrected_query_value", + applied_controls=["applied_controls_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 = search_service.SearchResponse.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 + response = client.search_lite(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchLitePager) + assert response.total_size == 1086 + assert response.attribution_token == "attribution_token_value" + assert response.redirect_uri == "redirect_uri_value" + assert response.next_page_token == "next_page_token_value" + assert response.corrected_query == "corrected_query_value" + assert response.applied_controls == ["applied_controls_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_lite_rest_interceptors(null_interceptor): + transport = transports.SearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SearchServiceRestInterceptor(), + ) + client = SearchServiceClient(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.SearchServiceRestInterceptor, "post_search_lite" + ) as post, mock.patch.object( + transports.SearchServiceRestInterceptor, "pre_search_lite" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) + 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 + return_value = search_service.SearchResponse.to_json( + search_service.SearchResponse() + ) + req.return_value.content = return_value + + request = search_service.SearchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = search_service.SearchResponse() + + client.search_lite( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + def test_cancel_operation_rest_bad_request( request_type=operations_pb2.CancelOperationRequest, ): @@ -2332,6 +3180,26 @@ def test_search_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_search_lite_empty_call_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_lite), "__call__") as call: + client.search_lite(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = SearchServiceClient( @@ -2366,6 +3234,7 @@ def test_search_service_base_transport(): # raise NotImplementedError. methods = ( "search", + "search_lite", "get_operation", "cancel_operation", "list_operations", @@ -2630,6 +3499,9 @@ def test_search_service_client_transport_session_collision(transport_name): session1 = client1.transport.search._session session2 = client2.transport.search._session assert session1 != session2 + session1 = client1.transport.search_lite._session + session2 = client2.transport.search_lite._session + assert session1 != session2 def test_search_service_grpc_transport_channel(): diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_serving_config_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_serving_config_service.py index 4ce3d09e444e..e6e8aa044abe 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_serving_config_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_serving_config_service.py @@ -3584,6 +3584,7 @@ def test_update_serving_config_rest_call_success(request_type): "content_watched_percentage_threshold": 0.3811, "content_watched_seconds_threshold": 0.3508, "demotion_event_type": "demotion_event_type_value", + "demote_content_watched_past_days": 3390, "content_freshness_cutoff_days": 3105, }, "generic_config": { @@ -3599,6 +3600,7 @@ def test_update_serving_config_rest_call_success(request_type): "ignore_adversarial_query": True, "ignore_non_summary_seeking_query": True, "ignore_low_relevant_content": True, + "ignore_jail_breaking_query": True, "model_prompt_spec": {"preamble": "preamble_value"}, "language_code": "language_code_value", "model_spec": {"version": "version_value"}, @@ -3653,6 +3655,7 @@ def test_update_serving_config_rest_call_success(request_type): "ignore_control_ids_value1", "ignore_control_ids_value2", ], + "personalization_spec": {"mode": 1}, } # 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-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_site_search_engine_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_site_search_engine_service.py index b8d298304869..80fb0292ea59 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_site_search_engine_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_site_search_engine_service.py @@ -3779,11 +3779,11 @@ async def test_list_target_sites_async_pages(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.EnableAdvancedSiteSearchRequest, + site_search_engine_service.CreateSitemapRequest, dict, ], ) -def test_enable_advanced_site_search(request_type, transport: str = "grpc"): +def test_create_sitemap(request_type, transport: str = "grpc"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3794,24 +3794,22 @@ def test_enable_advanced_site_search(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.enable_advanced_site_search(request) + response = client.create_sitemap(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = site_search_engine_service.EnableAdvancedSiteSearchRequest() + request = site_search_engine_service.CreateSitemapRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_enable_advanced_site_search_non_empty_request_with_auto_populated_field(): +def test_create_sitemap_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = SiteSearchEngineServiceClient( @@ -3822,26 +3820,24 @@ def test_enable_advanced_site_search_non_empty_request_with_auto_populated_field # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = site_search_engine_service.EnableAdvancedSiteSearchRequest( - site_search_engine="site_search_engine_value", + request = site_search_engine_service.CreateSitemapRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.enable_advanced_site_search(request=request) + client.create_sitemap(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == site_search_engine_service.EnableAdvancedSiteSearchRequest( - site_search_engine="site_search_engine_value", + assert args[0] == site_search_engine_service.CreateSitemapRequest( + parent="parent_value", ) -def test_enable_advanced_site_search_use_cached_wrapped_rpc(): +def test_create_sitemap_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: @@ -3855,21 +3851,16 @@ def test_enable_advanced_site_search_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.enable_advanced_site_search - in client._transport._wrapped_methods - ) + assert client._transport.create_sitemap 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.enable_advanced_site_search - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_sitemap] = mock_rpc request = {} - client.enable_advanced_site_search(request) + client.create_sitemap(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3879,7 +3870,7 @@ def test_enable_advanced_site_search_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.enable_advanced_site_search(request) + client.create_sitemap(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3887,7 +3878,7 @@ def test_enable_advanced_site_search_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_enable_advanced_site_search_async_use_cached_wrapped_rpc( +async def test_create_sitemap_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3904,7 +3895,7 @@ async def test_enable_advanced_site_search_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.enable_advanced_site_search + client._client._transport.create_sitemap in client._client._transport._wrapped_methods ) @@ -3912,11 +3903,11 @@ async def test_enable_advanced_site_search_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.enable_advanced_site_search + client._client._transport.create_sitemap ] = mock_rpc request = {} - await client.enable_advanced_site_search(request) + await client.create_sitemap(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3926,7 +3917,7 @@ async def test_enable_advanced_site_search_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.enable_advanced_site_search(request) + await client.create_sitemap(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3934,9 +3925,9 @@ async def test_enable_advanced_site_search_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_enable_advanced_site_search_async( +async def test_create_sitemap_async( transport: str = "grpc_asyncio", - request_type=site_search_engine_service.EnableAdvancedSiteSearchRequest, + request_type=site_search_engine_service.CreateSitemapRequest, ): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -3948,19 +3939,17 @@ async def test_enable_advanced_site_search_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.enable_advanced_site_search(request) + response = await client.create_sitemap(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = site_search_engine_service.EnableAdvancedSiteSearchRequest() + request = site_search_engine_service.CreateSitemapRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -3968,27 +3957,25 @@ async def test_enable_advanced_site_search_async( @pytest.mark.asyncio -async def test_enable_advanced_site_search_async_from_dict(): - await test_enable_advanced_site_search_async(request_type=dict) +async def test_create_sitemap_async_from_dict(): + await test_create_sitemap_async(request_type=dict) -def test_enable_advanced_site_search_field_headers(): +def test_create_sitemap_field_headers(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.EnableAdvancedSiteSearchRequest() + request = site_search_engine_service.CreateSitemapRequest() - request.site_search_engine = "site_search_engine_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.enable_advanced_site_search(request) + client.create_sitemap(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3999,30 +3986,28 @@ def test_enable_advanced_site_search_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "site_search_engine=site_search_engine_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_enable_advanced_site_search_field_headers_async(): +async def test_create_sitemap_field_headers_async(): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.EnableAdvancedSiteSearchRequest() + request = site_search_engine_service.CreateSitemapRequest() - request.site_search_engine = "site_search_engine_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.enable_advanced_site_search(request) + await client.create_sitemap(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4033,18 +4018,110 @@ async def test_enable_advanced_site_search_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "site_search_engine=site_search_engine_value", + "parent=parent_value", ) in kw["metadata"] +def test_create_sitemap_flattened(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_sitemap( + parent="parent_value", + sitemap=site_search_engine.Sitemap(uri="uri_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].sitemap + mock_val = site_search_engine.Sitemap(uri="uri_value") + assert arg == mock_val + + +def test_create_sitemap_flattened_error(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_sitemap( + site_search_engine_service.CreateSitemapRequest(), + parent="parent_value", + sitemap=site_search_engine.Sitemap(uri="uri_value"), + ) + + +@pytest.mark.asyncio +async def test_create_sitemap_flattened_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_sitemap( + parent="parent_value", + sitemap=site_search_engine.Sitemap(uri="uri_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].sitemap + mock_val = site_search_engine.Sitemap(uri="uri_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_sitemap_flattened_error_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_sitemap( + site_search_engine_service.CreateSitemapRequest(), + parent="parent_value", + sitemap=site_search_engine.Sitemap(uri="uri_value"), + ) + + @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.DisableAdvancedSiteSearchRequest, + site_search_engine_service.DeleteSitemapRequest, dict, ], ) -def test_disable_advanced_site_search(request_type, transport: str = "grpc"): +def test_delete_sitemap(request_type, transport: str = "grpc"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4055,24 +4132,22 @@ def test_disable_advanced_site_search(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.disable_advanced_site_search(request) + response = client.delete_sitemap(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = site_search_engine_service.DisableAdvancedSiteSearchRequest() + request = site_search_engine_service.DeleteSitemapRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_disable_advanced_site_search_non_empty_request_with_auto_populated_field(): +def test_delete_sitemap_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = SiteSearchEngineServiceClient( @@ -4083,26 +4158,24 @@ def test_disable_advanced_site_search_non_empty_request_with_auto_populated_fiel # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = site_search_engine_service.DisableAdvancedSiteSearchRequest( - site_search_engine="site_search_engine_value", + request = site_search_engine_service.DeleteSitemapRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.disable_advanced_site_search(request=request) + client.delete_sitemap(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == site_search_engine_service.DisableAdvancedSiteSearchRequest( - site_search_engine="site_search_engine_value", + assert args[0] == site_search_engine_service.DeleteSitemapRequest( + name="name_value", ) -def test_disable_advanced_site_search_use_cached_wrapped_rpc(): +def test_delete_sitemap_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: @@ -4116,21 +4189,16 @@ def test_disable_advanced_site_search_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.disable_advanced_site_search - in client._transport._wrapped_methods - ) + assert client._transport.delete_sitemap 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.disable_advanced_site_search - ] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_sitemap] = mock_rpc request = {} - client.disable_advanced_site_search(request) + client.delete_sitemap(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4140,7 +4208,7 @@ def test_disable_advanced_site_search_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.disable_advanced_site_search(request) + client.delete_sitemap(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4148,7 +4216,7 @@ def test_disable_advanced_site_search_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_disable_advanced_site_search_async_use_cached_wrapped_rpc( +async def test_delete_sitemap_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4165,7 +4233,7 @@ async def test_disable_advanced_site_search_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.disable_advanced_site_search + client._client._transport.delete_sitemap in client._client._transport._wrapped_methods ) @@ -4173,11 +4241,11 @@ async def test_disable_advanced_site_search_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.disable_advanced_site_search + client._client._transport.delete_sitemap ] = mock_rpc request = {} - await client.disable_advanced_site_search(request) + await client.delete_sitemap(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4187,7 +4255,7 @@ async def test_disable_advanced_site_search_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.disable_advanced_site_search(request) + await client.delete_sitemap(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4195,9 +4263,9 @@ async def test_disable_advanced_site_search_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_disable_advanced_site_search_async( +async def test_delete_sitemap_async( transport: str = "grpc_asyncio", - request_type=site_search_engine_service.DisableAdvancedSiteSearchRequest, + request_type=site_search_engine_service.DeleteSitemapRequest, ): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -4209,19 +4277,17 @@ async def test_disable_advanced_site_search_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.disable_advanced_site_search(request) + response = await client.delete_sitemap(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = site_search_engine_service.DisableAdvancedSiteSearchRequest() + request = site_search_engine_service.DeleteSitemapRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -4229,27 +4295,25 @@ async def test_disable_advanced_site_search_async( @pytest.mark.asyncio -async def test_disable_advanced_site_search_async_from_dict(): - await test_disable_advanced_site_search_async(request_type=dict) +async def test_delete_sitemap_async_from_dict(): + await test_delete_sitemap_async(request_type=dict) -def test_disable_advanced_site_search_field_headers(): +def test_delete_sitemap_field_headers(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.DisableAdvancedSiteSearchRequest() + request = site_search_engine_service.DeleteSitemapRequest() - request.site_search_engine = "site_search_engine_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.disable_advanced_site_search(request) + client.delete_sitemap(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4260,30 +4324,28 @@ def test_disable_advanced_site_search_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "site_search_engine=site_search_engine_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_disable_advanced_site_search_field_headers_async(): +async def test_delete_sitemap_field_headers_async(): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.DisableAdvancedSiteSearchRequest() + request = site_search_engine_service.DeleteSitemapRequest() - request.site_search_engine = "site_search_engine_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_advanced_site_search), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.disable_advanced_site_search(request) + await client.delete_sitemap(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4294,72 +4356,154 @@ async def test_disable_advanced_site_search_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "site_search_engine=site_search_engine_value", + "name=name_value", ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - site_search_engine_service.RecrawlUrisRequest, - dict, - ], -) -def test_recrawl_uris(request_type, transport: str = "grpc"): +def test_delete_sitemap_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.recrawl_uris(request) + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_sitemap( + name="name_value", + ) - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = site_search_engine_service.RecrawlUrisRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_recrawl_uris_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_delete_sitemap_flattened_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = site_search_engine_service.RecrawlUrisRequest( - site_search_engine="site_search_engine_value", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_sitemap( + site_search_engine_service.DeleteSitemapRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_sitemap_flattened_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - client.recrawl_uris(request=request) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_sitemap( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_sitemap_flattened_error_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_sitemap( + site_search_engine_service.DeleteSitemapRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.FetchSitemapsRequest, + dict, + ], +) +def test_fetch_sitemaps(request_type, transport: str = "grpc"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = site_search_engine_service.FetchSitemapsResponse() + response = client.fetch_sitemaps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.FetchSitemapsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, site_search_engine_service.FetchSitemapsResponse) + + +def test_fetch_sitemaps_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = site_search_engine_service.FetchSitemapsRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_sitemaps(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == site_search_engine_service.RecrawlUrisRequest( - site_search_engine="site_search_engine_value", + assert args[0] == site_search_engine_service.FetchSitemapsRequest( + parent="parent_value", ) -def test_recrawl_uris_use_cached_wrapped_rpc(): +def test_fetch_sitemaps_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: @@ -4373,26 +4517,21 @@ def test_recrawl_uris_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.recrawl_uris in client._transport._wrapped_methods + assert client._transport.fetch_sitemaps 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.recrawl_uris] = mock_rpc + client._transport._wrapped_methods[client._transport.fetch_sitemaps] = mock_rpc request = {} - client.recrawl_uris(request) + client.fetch_sitemaps(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.recrawl_uris(request) + client.fetch_sitemaps(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4400,7 +4539,7 @@ def test_recrawl_uris_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_recrawl_uris_async_use_cached_wrapped_rpc( +async def test_fetch_sitemaps_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4417,7 +4556,7 @@ async def test_recrawl_uris_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.recrawl_uris + client._client._transport.fetch_sitemaps in client._client._transport._wrapped_methods ) @@ -4425,21 +4564,16 @@ async def test_recrawl_uris_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.recrawl_uris + client._client._transport.fetch_sitemaps ] = mock_rpc request = {} - await client.recrawl_uris(request) + await client.fetch_sitemaps(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.recrawl_uris(request) + await client.fetch_sitemaps(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4447,9 +4581,9 @@ async def test_recrawl_uris_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_recrawl_uris_async( +async def test_fetch_sitemaps_async( transport: str = "grpc_asyncio", - request_type=site_search_engine_service.RecrawlUrisRequest, + request_type=site_search_engine_service.FetchSitemapsRequest, ): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -4461,43 +4595,43 @@ async def test_recrawl_uris_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + site_search_engine_service.FetchSitemapsResponse() ) - response = await client.recrawl_uris(request) + response = await client.fetch_sitemaps(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = site_search_engine_service.RecrawlUrisRequest() + request = site_search_engine_service.FetchSitemapsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, site_search_engine_service.FetchSitemapsResponse) @pytest.mark.asyncio -async def test_recrawl_uris_async_from_dict(): - await test_recrawl_uris_async(request_type=dict) +async def test_fetch_sitemaps_async_from_dict(): + await test_fetch_sitemaps_async(request_type=dict) -def test_recrawl_uris_field_headers(): +def test_fetch_sitemaps_field_headers(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.RecrawlUrisRequest() + request = site_search_engine_service.FetchSitemapsRequest() - request.site_search_engine = "site_search_engine_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.recrawl_uris(request) + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: + call.return_value = site_search_engine_service.FetchSitemapsResponse() + client.fetch_sitemaps(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4508,28 +4642,28 @@ def test_recrawl_uris_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "site_search_engine=site_search_engine_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_recrawl_uris_field_headers_async(): +async def test_fetch_sitemaps_field_headers_async(): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.RecrawlUrisRequest() + request = site_search_engine_service.FetchSitemapsRequest() - request.site_search_engine = "site_search_engine_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + site_search_engine_service.FetchSitemapsResponse() ) - await client.recrawl_uris(request) + await client.fetch_sitemaps(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4540,18 +4674,100 @@ async def test_recrawl_uris_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "site_search_engine=site_search_engine_value", + "parent=parent_value", ) in kw["metadata"] +def test_fetch_sitemaps_flattened(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = site_search_engine_service.FetchSitemapsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_sitemaps( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_fetch_sitemaps_flattened_error(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_sitemaps( + site_search_engine_service.FetchSitemapsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_fetch_sitemaps_flattened_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = site_search_engine_service.FetchSitemapsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.FetchSitemapsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_sitemaps( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_fetch_sitemaps_flattened_error_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.fetch_sitemaps( + site_search_engine_service.FetchSitemapsRequest(), + parent="parent_value", + ) + + @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.BatchVerifyTargetSitesRequest, + site_search_engine_service.EnableAdvancedSiteSearchRequest, dict, ], ) -def test_batch_verify_target_sites(request_type, transport: str = "grpc"): +def test_enable_advanced_site_search(request_type, transport: str = "grpc"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4563,23 +4779,23 @@ def test_batch_verify_target_sites(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_verify_target_sites), "__call__" + type(client.transport.enable_advanced_site_search), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_verify_target_sites(request) + response = client.enable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = site_search_engine_service.BatchVerifyTargetSitesRequest() + request = site_search_engine_service.EnableAdvancedSiteSearchRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_batch_verify_target_sites_non_empty_request_with_auto_populated_field(): +def test_enable_advanced_site_search_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = SiteSearchEngineServiceClient( @@ -4590,26 +4806,26 @@ def test_batch_verify_target_sites_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = site_search_engine_service.BatchVerifyTargetSitesRequest( - parent="parent_value", + request = site_search_engine_service.EnableAdvancedSiteSearchRequest( + site_search_engine="site_search_engine_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_verify_target_sites), "__call__" + type(client.transport.enable_advanced_site_search), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.batch_verify_target_sites(request=request) + client.enable_advanced_site_search(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == site_search_engine_service.BatchVerifyTargetSitesRequest( - parent="parent_value", + assert args[0] == site_search_engine_service.EnableAdvancedSiteSearchRequest( + site_search_engine="site_search_engine_value", ) -def test_batch_verify_target_sites_use_cached_wrapped_rpc(): +def test_enable_advanced_site_search_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: @@ -4624,7 +4840,7 @@ def test_batch_verify_target_sites_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_verify_target_sites + client._transport.enable_advanced_site_search in client._transport._wrapped_methods ) @@ -4634,10 +4850,10 @@ def test_batch_verify_target_sites_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_verify_target_sites + client._transport.enable_advanced_site_search ] = mock_rpc request = {} - client.batch_verify_target_sites(request) + client.enable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4647,7 +4863,7 @@ def test_batch_verify_target_sites_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.batch_verify_target_sites(request) + client.enable_advanced_site_search(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4655,7 +4871,7 @@ def test_batch_verify_target_sites_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_batch_verify_target_sites_async_use_cached_wrapped_rpc( +async def test_enable_advanced_site_search_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4672,7 +4888,7 @@ async def test_batch_verify_target_sites_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.batch_verify_target_sites + client._client._transport.enable_advanced_site_search in client._client._transport._wrapped_methods ) @@ -4680,11 +4896,11 @@ async def test_batch_verify_target_sites_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.batch_verify_target_sites + client._client._transport.enable_advanced_site_search ] = mock_rpc request = {} - await client.batch_verify_target_sites(request) + await client.enable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4694,7 +4910,7 @@ async def test_batch_verify_target_sites_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.batch_verify_target_sites(request) + await client.enable_advanced_site_search(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4702,9 +4918,9 @@ async def test_batch_verify_target_sites_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_batch_verify_target_sites_async( +async def test_enable_advanced_site_search_async( transport: str = "grpc_asyncio", - request_type=site_search_engine_service.BatchVerifyTargetSitesRequest, + request_type=site_search_engine_service.EnableAdvancedSiteSearchRequest, ): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -4717,18 +4933,18 @@ async def test_batch_verify_target_sites_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_verify_target_sites), "__call__" + type(client.transport.enable_advanced_site_search), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_verify_target_sites(request) + response = await client.enable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = site_search_engine_service.BatchVerifyTargetSitesRequest() + request = site_search_engine_service.EnableAdvancedSiteSearchRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -4736,27 +4952,27 @@ async def test_batch_verify_target_sites_async( @pytest.mark.asyncio -async def test_batch_verify_target_sites_async_from_dict(): - await test_batch_verify_target_sites_async(request_type=dict) +async def test_enable_advanced_site_search_async_from_dict(): + await test_enable_advanced_site_search_async(request_type=dict) -def test_batch_verify_target_sites_field_headers(): +def test_enable_advanced_site_search_field_headers(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.BatchVerifyTargetSitesRequest() + request = site_search_engine_service.EnableAdvancedSiteSearchRequest() - request.parent = "parent_value" + request.site_search_engine = "site_search_engine_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_verify_target_sites), "__call__" + type(client.transport.enable_advanced_site_search), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_verify_target_sites(request) + client.enable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4767,30 +4983,30 @@ def test_batch_verify_target_sites_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "site_search_engine=site_search_engine_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_batch_verify_target_sites_field_headers_async(): +async def test_enable_advanced_site_search_field_headers_async(): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.BatchVerifyTargetSitesRequest() + request = site_search_engine_service.EnableAdvancedSiteSearchRequest() - request.parent = "parent_value" + request.site_search_engine = "site_search_engine_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_verify_target_sites), "__call__" + type(client.transport.enable_advanced_site_search), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_verify_target_sites(request) + await client.enable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4801,18 +5017,18 @@ async def test_batch_verify_target_sites_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "site_search_engine=site_search_engine_value", ) in kw["metadata"] @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.FetchDomainVerificationStatusRequest, + site_search_engine_service.DisableAdvancedSiteSearchRequest, dict, ], ) -def test_fetch_domain_verification_status(request_type, transport: str = "grpc"): +def test_disable_advanced_site_search(request_type, transport: str = "grpc"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4824,30 +5040,23 @@ def test_fetch_domain_verification_status(request_type, transport: str = "grpc") # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" + type(client.transport.disable_advanced_site_search), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - site_search_engine_service.FetchDomainVerificationStatusResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) - ) - response = client.fetch_domain_verification_status(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.disable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = site_search_engine_service.FetchDomainVerificationStatusRequest() + request = site_search_engine_service.DisableAdvancedSiteSearchRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchDomainVerificationStatusPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert isinstance(response, future.Future) -def test_fetch_domain_verification_status_non_empty_request_with_auto_populated_field(): +def test_disable_advanced_site_search_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = SiteSearchEngineServiceClient( @@ -4858,30 +5067,26 @@ def test_fetch_domain_verification_status_non_empty_request_with_auto_populated_ # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = site_search_engine_service.FetchDomainVerificationStatusRequest( + request = site_search_engine_service.DisableAdvancedSiteSearchRequest( site_search_engine="site_search_engine_value", - page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" + type(client.transport.disable_advanced_site_search), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_domain_verification_status(request=request) + client.disable_advanced_site_search(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[ - 0 - ] == site_search_engine_service.FetchDomainVerificationStatusRequest( + assert args[0] == site_search_engine_service.DisableAdvancedSiteSearchRequest( site_search_engine="site_search_engine_value", - page_token="page_token_value", ) -def test_fetch_domain_verification_status_use_cached_wrapped_rpc(): +def test_disable_advanced_site_search_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: @@ -4896,7 +5101,7 @@ def test_fetch_domain_verification_status_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_domain_verification_status + client._transport.disable_advanced_site_search in client._transport._wrapped_methods ) @@ -4906,15 +5111,20 @@ def test_fetch_domain_verification_status_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_domain_verification_status + client._transport.disable_advanced_site_search ] = mock_rpc request = {} - client.fetch_domain_verification_status(request) + client.disable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_domain_verification_status(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.disable_advanced_site_search(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4922,7 +5132,7 @@ def test_fetch_domain_verification_status_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_fetch_domain_verification_status_async_use_cached_wrapped_rpc( +async def test_disable_advanced_site_search_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4939,7 +5149,7 @@ async def test_fetch_domain_verification_status_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.fetch_domain_verification_status + client._client._transport.disable_advanced_site_search in client._client._transport._wrapped_methods ) @@ -4947,16 +5157,21 @@ async def test_fetch_domain_verification_status_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_domain_verification_status + client._client._transport.disable_advanced_site_search ] = mock_rpc request = {} - await client.fetch_domain_verification_status(request) + await client.disable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_domain_verification_status(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.disable_advanced_site_search(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4964,9 +5179,9 @@ async def test_fetch_domain_verification_status_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_fetch_domain_verification_status_async( +async def test_disable_advanced_site_search_async( transport: str = "grpc_asyncio", - request_type=site_search_engine_service.FetchDomainVerificationStatusRequest, + request_type=site_search_engine_service.DisableAdvancedSiteSearchRequest, ): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), @@ -4979,53 +5194,46 @@ async def test_fetch_domain_verification_status_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" + type(client.transport.disable_advanced_site_search), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - site_search_engine_service.FetchDomainVerificationStatusResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.fetch_domain_verification_status(request) + response = await client.disable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = site_search_engine_service.FetchDomainVerificationStatusRequest() + request = site_search_engine_service.DisableAdvancedSiteSearchRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchDomainVerificationStatusAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_fetch_domain_verification_status_async_from_dict(): - await test_fetch_domain_verification_status_async(request_type=dict) +async def test_disable_advanced_site_search_async_from_dict(): + await test_disable_advanced_site_search_async(request_type=dict) -def test_fetch_domain_verification_status_field_headers(): +def test_disable_advanced_site_search_field_headers(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.FetchDomainVerificationStatusRequest() + request = site_search_engine_service.DisableAdvancedSiteSearchRequest() request.site_search_engine = "site_search_engine_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" + type(client.transport.disable_advanced_site_search), "__call__" ) as call: - call.return_value = ( - site_search_engine_service.FetchDomainVerificationStatusResponse() - ) - client.fetch_domain_verification_status(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.disable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5041,25 +5249,25 @@ def test_fetch_domain_verification_status_field_headers(): @pytest.mark.asyncio -async def test_fetch_domain_verification_status_field_headers_async(): +async def test_disable_advanced_site_search_field_headers_async(): client = SiteSearchEngineServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = site_search_engine_service.FetchDomainVerificationStatusRequest() + request = site_search_engine_service.DisableAdvancedSiteSearchRequest() request.site_search_engine = "site_search_engine_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" + type(client.transport.disable_advanced_site_search), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - site_search_engine_service.FetchDomainVerificationStatusResponse() + operations_pb2.Operation(name="operations/op") ) - await client.fetch_domain_verification_status(request) + await client.disable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5074,217 +5282,76 @@ async def test_fetch_domain_verification_status_field_headers_async(): ) in kw["metadata"] -def test_fetch_domain_verification_status_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.RecrawlUrisRequest, + dict, + ], +) +def test_recrawl_uris(request_type, transport: str = "grpc"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - next_page_token="abc", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[], - next_page_token="def", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - ], - next_page_token="ghi", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - ), - RuntimeError, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("site_search_engine", ""),)), - ) - pager = client.fetch_domain_verification_status( - request={}, retry=retry, timeout=timeout - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.recrawl_uris(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.RecrawlUrisRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, site_search_engine.TargetSite) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_fetch_domain_verification_status_pages(transport_name: str = "grpc"): +def test_recrawl_uris_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = site_search_engine_service.RecrawlUrisRequest( + site_search_engine="site_search_engine_value", + site_credential="site_credential_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - next_page_token="abc", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[], - next_page_token="def", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - ], - next_page_token="ghi", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - ), - RuntimeError, + with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.recrawl_uris(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.RecrawlUrisRequest( + site_search_engine="site_search_engine_value", + site_credential="site_credential_value", ) - pages = list(client.fetch_domain_verification_status(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_fetch_domain_verification_status_async_pager(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_domain_verification_status), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - next_page_token="abc", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[], - next_page_token="def", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - ], - next_page_token="ghi", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - ), - RuntimeError, - ) - async_pager = await client.fetch_domain_verification_status( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, site_search_engine.TargetSite) for i in responses) - - -@pytest.mark.asyncio -async def test_fetch_domain_verification_status_async_pages(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_domain_verification_status), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - next_page_token="abc", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[], - next_page_token="def", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - ], - next_page_token="ghi", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.fetch_domain_verification_status(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_site_search_engine_rest_use_cached_wrapped_rpc(): +def test_recrawl_uris_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 = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5292,182 +5359,249 @@ def test_get_site_search_engine_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_site_search_engine - in client._transport._wrapped_methods - ) + assert client._transport.recrawl_uris 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_site_search_engine - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.recrawl_uris] = mock_rpc request = {} - client.get_site_search_engine(request) + client.recrawl_uris(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_site_search_engine(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.recrawl_uris(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_site_search_engine_rest_required_fields( - request_type=site_search_engine_service.GetSiteSearchEngineRequest, +@pytest.mark.asyncio +async def test_recrawl_uris_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.SiteSearchEngineServiceRestTransport - - request_init = {} - request_init["name"] = "" - 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) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_site_search_engine._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.recrawl_uris + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.recrawl_uris + ] = mock_rpc - jsonified_request["name"] = "name_value" + request = {} + await client.recrawl_uris(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_site_search_engine._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.recrawl_uris(request) - # Designate an appropriate value for the returned response. - return_value = site_search_engine.SiteSearchEngine() - # 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 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = site_search_engine.SiteSearchEngine.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_recrawl_uris_async( + transport: str = "grpc_asyncio", + request_type=site_search_engine_service.RecrawlUrisRequest, +): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.get_site_search_engine(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.recrawl_uris(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.RecrawlUrisRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_get_site_search_engine_rest_unset_required_fields(): - transport = transports.SiteSearchEngineServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.get_site_search_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) +@pytest.mark.asyncio +async def test_recrawl_uris_async_from_dict(): + await test_recrawl_uris_async(request_type=dict) -def test_get_site_search_engine_rest_flattened(): +def test_recrawl_uris_field_headers(): client = SiteSearchEngineServiceClient( 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 = site_search_engine.SiteSearchEngine() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.RecrawlUrisRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" - } + request.site_search_engine = "site_search_engine_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.recrawl_uris(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 = site_search_engine.SiteSearchEngine.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 + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_site_search_engine(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "site_search_engine=site_search_engine_value", + ) in kw["metadata"] - # 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/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine}" - % client.transport._host, - args[1], + +@pytest.mark.asyncio +async def test_recrawl_uris_field_headers_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.RecrawlUrisRequest() + + request.site_search_engine = "site_search_engine_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) + await client.recrawl_uris(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "site_search_engine=site_search_engine_value", + ) in kw["metadata"] -def test_get_site_search_engine_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.BatchVerifyTargetSitesRequest, + dict, + ], +) +def test_batch_verify_target_sites(request_type, transport: str = "grpc"): client = SiteSearchEngineServiceClient( 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_site_search_engine( - site_search_engine_service.GetSiteSearchEngineRequest(), - name="name_value", + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_verify_target_sites), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.batch_verify_target_sites(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.BatchVerifyTargetSitesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_verify_target_sites_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = site_search_engine_service.BatchVerifyTargetSitesRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_verify_target_sites), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_verify_target_sites(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.BatchVerifyTargetSitesRequest( + parent="parent_value", ) -def test_create_target_site_rest_use_cached_wrapped_rpc(): +def test_batch_verify_target_sites_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 = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5476,7 +5610,8 @@ def test_create_target_site_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_target_site in client._transport._wrapped_methods + client._transport.batch_verify_target_sites + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5485,181 +5620,260 @@ def test_create_target_site_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_target_site + client._transport.batch_verify_target_sites ] = mock_rpc - request = {} - client.create_target_site(request) + client.batch_verify_target_sites(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 + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_target_site(request) + client.batch_verify_target_sites(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_create_target_site_rest_required_fields( - request_type=site_search_engine_service.CreateTargetSiteRequest, +@pytest.mark.asyncio +async def test_batch_verify_target_sites_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.SiteSearchEngineServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_target_site._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.batch_verify_target_sites + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_verify_target_sites + ] = mock_rpc - jsonified_request["parent"] = "parent_value" + request = {} + await client.batch_verify_target_sites(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_target_site._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.batch_verify_target_sites(request) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.asyncio +async def test_batch_verify_target_sites_async( + transport: str = "grpc_asyncio", + request_type=site_search_engine_service.BatchVerifyTargetSitesRequest, +): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response = client.create_target_site(request) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_verify_target_sites), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.batch_verify_target_sites(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.BatchVerifyTargetSitesRequest() + assert args[0] == request -def test_create_target_site_rest_unset_required_fields(): - transport = transports.SiteSearchEngineServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - unset_fields = transport.create_target_site._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "targetSite", - ) - ) - ) +@pytest.mark.asyncio +async def test_batch_verify_target_sites_async_from_dict(): + await test_batch_verify_target_sites_async(request_type=dict) -def test_create_target_site_rest_flattened(): + +def test_batch_verify_target_sites_field_headers(): client = SiteSearchEngineServiceClient( 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 = operations_pb2.Operation(name="operations/spam") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.BatchVerifyTargetSitesRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - target_site=site_search_engine.TargetSite(name="name_value"), - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_verify_target_sites), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.batch_verify_target_sites(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.create_target_site(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # 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/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites" - % client.transport._host, - args[1], + +@pytest.mark.asyncio +async def test_batch_verify_target_sites_field_headers_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.BatchVerifyTargetSitesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_verify_target_sites), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) + await client.batch_verify_target_sites(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_create_target_site_rest_flattened_error(transport: str = "rest"): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.FetchDomainVerificationStatusRequest, + dict, + ], +) +def test_fetch_domain_verification_status(request_type, transport: str = "grpc"): client = SiteSearchEngineServiceClient( 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.create_target_site( - site_search_engine_service.CreateTargetSiteRequest(), - parent="parent_value", - target_site=site_search_engine.TargetSite(name="name_value"), + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + site_search_engine_service.FetchDomainVerificationStatusResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) ) + response = client.fetch_domain_verification_status(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.FetchDomainVerificationStatusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchDomainVerificationStatusPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 -def test_batch_create_target_sites_rest_use_cached_wrapped_rpc(): +def test_fetch_domain_verification_status_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = site_search_engine_service.FetchDomainVerificationStatusRequest( + site_search_engine="site_search_engine_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_domain_verification_status(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[ + 0 + ] == site_search_engine_service.FetchDomainVerificationStatusRequest( + site_search_engine="site_search_engine_value", + page_token="page_token_value", + ) + + +def test_fetch_domain_verification_status_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 = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5668,7 +5882,7 @@ def test_batch_create_target_sites_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_create_target_sites + client._transport.fetch_domain_verification_status in client._transport._wrapped_methods ) @@ -5678,294 +5892,379 @@ def test_batch_create_target_sites_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_create_target_sites + client._transport.fetch_domain_verification_status ] = mock_rpc - request = {} - client.batch_create_target_sites(request) + client.fetch_domain_verification_status(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.batch_create_target_sites(request) + client.fetch_domain_verification_status(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_batch_create_target_sites_rest_required_fields( - request_type=site_search_engine_service.BatchCreateTargetSitesRequest, +@pytest.mark.asyncio +async def test_fetch_domain_verification_status_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.SiteSearchEngineServiceRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.fetch_domain_verification_status + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_create_target_sites._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_create_target_sites._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.batch_create_target_sites(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_batch_create_target_sites_rest_unset_required_fields(): - transport = transports.SiteSearchEngineServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.batch_create_target_sites._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "requests", - ) - ) - ) - - -def test_get_target_site_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 = SiteSearchEngineServiceClient( - 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_target_site 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_target_site] = mock_rpc + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.fetch_domain_verification_status + ] = mock_rpc request = {} - client.get_target_site(request) + await client.fetch_domain_verification_status(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_target_site(request) + await client.fetch_domain_verification_status(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_target_site_rest_required_fields( - request_type=site_search_engine_service.GetTargetSiteRequest, +@pytest.mark.asyncio +async def test_fetch_domain_verification_status_async( + transport: str = "grpc_asyncio", + request_type=site_search_engine_service.FetchDomainVerificationStatusRequest, ): - transport_class = transports.SiteSearchEngineServiceRestTransport - - request_init = {} - request_init["name"] = "" - 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) + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_target_site._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.FetchDomainVerificationStatusResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + response = await client.fetch_domain_verification_status(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.FetchDomainVerificationStatusRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchDomainVerificationStatusAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_target_site._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.asyncio +async def test_fetch_domain_verification_status_async_from_dict(): + await test_fetch_domain_verification_status_async(request_type=dict) + +def test_fetch_domain_verification_status_field_headers(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = site_search_engine.TargetSite() - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.FetchDomainVerificationStatusRequest() - # Convert return value to protobuf type - return_value = site_search_engine.TargetSite.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.site_search_engine = "site_search_engine_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + call.return_value = ( + site_search_engine_service.FetchDomainVerificationStatusResponse() + ) + client.fetch_domain_verification_status(request) - response = client.get_target_site(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "site_search_engine=site_search_engine_value", + ) in kw["metadata"] -def test_get_target_site_rest_unset_required_fields(): - transport = transports.SiteSearchEngineServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_fetch_domain_verification_status_field_headers_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.get_target_site._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.FetchDomainVerificationStatusRequest() + request.site_search_engine = "site_search_engine_value" -def test_get_target_site_rest_flattened(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.FetchDomainVerificationStatusResponse() + ) + await client.fetch_domain_verification_status(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "site_search_engine=site_search_engine_value", + ) in kw["metadata"] + + +def test_fetch_domain_verification_status_pager(transport_name: str = "grpc"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # 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 = site_search_engine.TargetSite() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + next_page_token="abc", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[], + next_page_token="def", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + ], + next_page_token="ghi", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + ), + RuntimeError, ) - 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 = site_search_engine.TargetSite.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 + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("site_search_engine", ""),)), + ) + pager = client.fetch_domain_verification_status( + request={}, retry=retry, timeout=timeout + ) - client.get_target_site(**mock_args) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # 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/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" - % client.transport._host, - args[1], - ) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, site_search_engine.TargetSite) for i in results) -def test_get_target_site_rest_flattened_error(transport: str = "rest"): +def test_fetch_domain_verification_status_pages(transport_name: str = "grpc"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_target_site( - site_search_engine_service.GetTargetSiteRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + next_page_token="abc", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[], + next_page_token="def", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + ], + next_page_token="ghi", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + ), + RuntimeError, ) + pages = list(client.fetch_domain_verification_status(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_update_target_site_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_fetch_domain_verification_status_async_pager(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + next_page_token="abc", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[], + next_page_token="def", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + ], + next_page_token="ghi", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_domain_verification_status( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, site_search_engine.TargetSite) for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_domain_verification_status_async_pages(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + next_page_token="abc", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[], + next_page_token="def", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + ], + next_page_token="ghi", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.fetch_domain_verification_status(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_site_search_engine_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: @@ -5980,7 +6279,8 @@ def test_update_target_site_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_target_site in client._transport._wrapped_methods + client._transport.get_site_search_engine + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5989,32 +6289,29 @@ def test_update_target_site_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_target_site + client._transport.get_site_search_engine ] = mock_rpc request = {} - client.update_target_site(request) + client.get_site_search_engine(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_target_site(request) + client.get_site_search_engine(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_target_site_rest_required_fields( - request_type=site_search_engine_service.UpdateTargetSiteRequest, +def test_get_site_search_engine_rest_required_fields( + request_type=site_search_engine_service.GetSiteSearchEngineRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6025,17 +6322,21 @@ def test_update_target_site_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_target_site._get_unset_required_fields(jsonified_request) + ).get_site_search_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_target_site._get_unset_required_fields(jsonified_request) + ).get_site_search_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6044,7 +6345,7 @@ def test_update_target_site_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine.SiteSearchEngine() # 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 @@ -6056,36 +6357,38 @@ def test_update_target_site_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "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 = site_search_engine.SiteSearchEngine.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 - response = client.update_target_site(request) + response = client.get_site_search_engine(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_target_site_rest_unset_required_fields(): +def test_get_site_search_engine_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_target_site._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("targetSite",))) + unset_fields = transport.get_site_search_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_target_site_rest_flattened(): +def test_get_site_search_engine_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6094,42 +6397,42 @@ def test_update_target_site_rest_flattened(): # 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 = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine.SiteSearchEngine() # get arguments that satisfy an http rule for this method sample_request = { - "target_site": { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } # get truthy value for each flattened field mock_args = dict( - target_site=site_search_engine.TargetSite(name="name_value"), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine.SiteSearchEngine.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 - client.update_target_site(**mock_args) + client.get_site_search_engine(**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/v1beta/{target_site.name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" + "%s/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine}" % client.transport._host, args[1], ) -def test_update_target_site_rest_flattened_error(transport: str = "rest"): +def test_get_site_search_engine_rest_flattened_error(transport: str = "rest"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6138,13 +6441,13 @@ def test_update_target_site_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_target_site( - site_search_engine_service.UpdateTargetSiteRequest(), - target_site=site_search_engine.TargetSite(name="name_value"), + client.get_site_search_engine( + site_search_engine_service.GetSiteSearchEngineRequest(), + name="name_value", ) -def test_delete_target_site_rest_use_cached_wrapped_rpc(): +def test_create_target_site_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: @@ -6159,7 +6462,7 @@ def test_delete_target_site_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_target_site in client._transport._wrapped_methods + client._transport.create_target_site in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6168,11 +6471,11 @@ def test_delete_target_site_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_target_site + client._transport.create_target_site ] = mock_rpc request = {} - client.delete_target_site(request) + client.create_target_site(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6181,20 +6484,20 @@ def test_delete_target_site_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_target_site(request) + client.create_target_site(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_target_site_rest_required_fields( - request_type=site_search_engine_service.DeleteTargetSiteRequest, +def test_create_target_site_rest_required_fields( + request_type=site_search_engine_service.CreateTargetSiteRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6205,21 +6508,21 @@ def test_delete_target_site_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_target_site._get_unset_required_fields(jsonified_request) + ).create_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_target_site._get_unset_required_fields(jsonified_request) + ).create_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6240,9 +6543,10 @@ def test_delete_target_site_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -6252,23 +6556,31 @@ def test_delete_target_site_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_target_site(request) + response = client.create_target_site(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_target_site_rest_unset_required_fields(): +def test_create_target_site_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_target_site._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_target_site._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "targetSite", + ) + ) + ) -def test_delete_target_site_rest_flattened(): +def test_create_target_site_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6281,12 +6593,13 @@ def test_delete_target_site_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + target_site=site_search_engine.TargetSite(name="name_value"), ) mock_args.update(sample_request) @@ -6297,20 +6610,20 @@ def test_delete_target_site_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_target_site(**mock_args) + client.create_target_site(**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/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" + "%s/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites" % client.transport._host, args[1], ) -def test_delete_target_site_rest_flattened_error(transport: str = "rest"): +def test_create_target_site_rest_flattened_error(transport: str = "rest"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6319,13 +6632,14 @@ def test_delete_target_site_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_target_site( - site_search_engine_service.DeleteTargetSiteRequest(), - name="name_value", + client.create_target_site( + site_search_engine_service.CreateTargetSiteRequest(), + parent="parent_value", + target_site=site_search_engine.TargetSite(name="name_value"), ) -def test_list_target_sites_rest_use_cached_wrapped_rpc(): +def test_batch_create_target_sites_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: @@ -6339,7 +6653,10 @@ def test_list_target_sites_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_target_sites in client._transport._wrapped_methods + assert ( + client._transport.batch_create_target_sites + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -6347,24 +6664,28 @@ def test_list_target_sites_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_target_sites + client._transport.batch_create_target_sites ] = mock_rpc request = {} - client.list_target_sites(request) + client.batch_create_target_sites(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_target_sites(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_create_target_sites(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_target_sites_rest_required_fields( - request_type=site_search_engine_service.ListTargetSitesRequest, +def test_batch_create_target_sites_rest_required_fields( + request_type=site_search_engine_service.BatchCreateTargetSitesRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport @@ -6380,7 +6701,7 @@ def test_list_target_sites_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_target_sites._get_unset_required_fields(jsonified_request) + ).batch_create_target_sites._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6389,14 +6710,7 @@ def test_list_target_sites_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_target_sites._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).batch_create_target_sites._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6410,7 +6724,7 @@ def test_list_target_sites_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = site_search_engine_service.ListTargetSitesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # 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 @@ -6422,175 +6736,222 @@ def test_list_target_sites_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "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 = site_search_engine_service.ListTargetSitesResponse.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 - response = client.list_target_sites(request) + response = client.batch_create_target_sites(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_target_sites_rest_unset_required_fields(): +def test_batch_create_target_sites_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_target_sites._get_unset_required_fields({}) + unset_fields = transport.batch_create_target_sites._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "parent", + "requests", ) ) - & set(("parent",)) ) -def test_list_target_sites_rest_flattened(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_get_target_site_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 = SiteSearchEngineServiceClient( + 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 = site_search_engine_service.ListTargetSitesResponse() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" - } + # Ensure method has been cached + assert client._transport.get_target_site in client._transport._wrapped_methods - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # 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. ) - mock_args.update(sample_request) + client._transport._wrapped_methods[client._transport.get_target_site] = mock_rpc - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = site_search_engine_service.ListTargetSitesResponse.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 + request = {} + client.get_target_site(request) - client.list_target_sites(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # 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/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites" - % client.transport._host, - args[1], - ) + client.get_target_site(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_target_sites_rest_flattened_error(transport: str = "rest"): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + +def test_get_target_site_rest_required_fields( + request_type=site_search_engine_service.GetTargetSiteRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport + + request_init = {} + request_init["name"] = "" + 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) ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_target_sites( - site_search_engine_service.ListTargetSitesRequest(), - parent="parent_value", - ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_target_site._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_target_site._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_list_target_sites_rest_pager(transport: str = "rest"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = site_search_engine.TargetSite() # 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 = ( - site_search_engine_service.ListTargetSitesResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - next_page_token="abc", - ), - site_search_engine_service.ListTargetSitesResponse( - target_sites=[], - next_page_token="def", - ), - site_search_engine_service.ListTargetSitesResponse( - target_sites=[ - site_search_engine.TargetSite(), - ], - next_page_token="ghi", - ), - site_search_engine_service.ListTargetSitesResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - site_search_engine_service.ListTargetSitesResponse.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 + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = site_search_engine.TargetSite.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 + + response = client.get_target_site(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_target_site_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_target_site._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_target_site_rest_flattened(): + client = SiteSearchEngineServiceClient( + 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 = site_search_engine.TargetSite() + + # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" } - pager = client.list_target_sites(request=sample_request) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, site_search_engine.TargetSite) for i in results) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine.TargetSite.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 - pages = list(client.list_target_sites(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.get_target_site(**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/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" + % client.transport._host, + args[1], + ) -def test_enable_advanced_site_search_rest_use_cached_wrapped_rpc(): + +def test_get_target_site_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + 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_target_site( + site_search_engine_service.GetTargetSiteRequest(), + name="name_value", + ) + + +def test_update_target_site_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: @@ -6605,8 +6966,7 @@ def test_enable_advanced_site_search_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.enable_advanced_site_search - in client._transport._wrapped_methods + client._transport.update_target_site in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6615,11 +6975,11 @@ def test_enable_advanced_site_search_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.enable_advanced_site_search + client._transport.update_target_site ] = mock_rpc request = {} - client.enable_advanced_site_search(request) + client.update_target_site(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6628,20 +6988,19 @@ def test_enable_advanced_site_search_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.enable_advanced_site_search(request) + client.update_target_site(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_enable_advanced_site_search_rest_required_fields( - request_type=site_search_engine_service.EnableAdvancedSiteSearchRequest, +def test_update_target_site_rest_required_fields( + request_type=site_search_engine_service.UpdateTargetSiteRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["site_search_engine"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6652,21 +7011,17 @@ def test_enable_advanced_site_search_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).enable_advanced_site_search._get_unset_required_fields(jsonified_request) + ).update_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["siteSearchEngine"] = "site_search_engine_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).enable_advanced_site_search._get_unset_required_fields(jsonified_request) + ).update_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "siteSearchEngine" in jsonified_request - assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6687,7 +7042,7 @@ def test_enable_advanced_site_search_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6700,23 +7055,82 @@ def test_enable_advanced_site_search_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.enable_advanced_site_search(request) + response = client.update_target_site(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_enable_advanced_site_search_rest_unset_required_fields(): +def test_update_target_site_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.enable_advanced_site_search._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) + unset_fields = transport.update_target_site._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("targetSite",))) -def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): +def test_update_target_site_rest_flattened(): + client = SiteSearchEngineServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "target_site": { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + target_site=site_search_engine.TargetSite(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_target_site(**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/v1beta/{target_site.name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" + % client.transport._host, + args[1], + ) + + +def test_update_target_site_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + 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_target_site( + site_search_engine_service.UpdateTargetSiteRequest(), + target_site=site_search_engine.TargetSite(name="name_value"), + ) + + +def test_delete_target_site_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: @@ -6731,8 +7145,7 @@ def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.disable_advanced_site_search - in client._transport._wrapped_methods + client._transport.delete_target_site in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6741,11 +7154,11 @@ def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.disable_advanced_site_search + client._transport.delete_target_site ] = mock_rpc request = {} - client.disable_advanced_site_search(request) + client.delete_target_site(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6754,20 +7167,20 @@ def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.disable_advanced_site_search(request) + client.delete_target_site(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_disable_advanced_site_search_rest_required_fields( - request_type=site_search_engine_service.DisableAdvancedSiteSearchRequest, +def test_delete_target_site_rest_required_fields( + request_type=site_search_engine_service.DeleteTargetSiteRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["site_search_engine"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6778,21 +7191,21 @@ def test_disable_advanced_site_search_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).disable_advanced_site_search._get_unset_required_fields(jsonified_request) + ).delete_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["siteSearchEngine"] = "site_search_engine_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).disable_advanced_site_search._get_unset_required_fields(jsonified_request) + ).delete_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "siteSearchEngine" in jsonified_request - assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6813,10 +7226,9 @@ def test_disable_advanced_site_search_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -6826,156 +7238,80 @@ def test_disable_advanced_site_search_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.disable_advanced_site_search(request) + response = client.delete_target_site(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_disable_advanced_site_search_rest_unset_required_fields(): +def test_delete_target_site_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.disable_advanced_site_search._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) - - -def test_recrawl_uris_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 = SiteSearchEngineServiceClient( - 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.recrawl_uris 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.recrawl_uris] = mock_rpc - - request = {} - client.recrawl_uris(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.recrawl_uris(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_recrawl_uris_rest_required_fields( - request_type=site_search_engine_service.RecrawlUrisRequest, -): - transport_class = transports.SiteSearchEngineServiceRestTransport - - request_init = {} - request_init["site_search_engine"] = "" - request_init["uris"] = "" - 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() - ).recrawl_uris._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["siteSearchEngine"] = "site_search_engine_value" - jsonified_request["uris"] = "uris_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).recrawl_uris._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + unset_fields = transport.delete_target_site._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) - # verify required fields with non-default values are left alone - assert "siteSearchEngine" in jsonified_request - assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" - assert "uris" in jsonified_request - assert jsonified_request["uris"] == "uris_value" +def test_delete_target_site_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") # 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 + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + } - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - response = client.recrawl_uris(request) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + client.delete_target_site(**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/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" + % client.transport._host, + args[1], + ) -def test_recrawl_uris_rest_unset_required_fields(): - transport = transports.SiteSearchEngineServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_delete_target_site_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - unset_fields = transport.recrawl_uris._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "siteSearchEngine", - "uris", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_target_site( + site_search_engine_service.DeleteTargetSiteRequest(), + name="name_value", ) - ) -def test_batch_verify_target_sites_rest_use_cached_wrapped_rpc(): +def test_list_target_sites_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: @@ -6989,10 +7325,7 @@ def test_batch_verify_target_sites_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_verify_target_sites - in client._transport._wrapped_methods - ) + assert client._transport.list_target_sites in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -7000,28 +7333,24 @@ def test_batch_verify_target_sites_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_verify_target_sites + client._transport.list_target_sites ] = mock_rpc request = {} - client.batch_verify_target_sites(request) + client.list_target_sites(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.batch_verify_target_sites(request) + client.list_target_sites(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_batch_verify_target_sites_rest_required_fields( - request_type=site_search_engine_service.BatchVerifyTargetSitesRequest, +def test_list_target_sites_rest_required_fields( + request_type=site_search_engine_service.ListTargetSitesRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport @@ -7037,7 +7366,7 @@ def test_batch_verify_target_sites_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_verify_target_sites._get_unset_required_fields(jsonified_request) + ).list_target_sites._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -7046,7 +7375,14 @@ def test_batch_verify_target_sites_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_verify_target_sites._get_unset_required_fields(jsonified_request) + ).list_target_sites._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -7060,7 +7396,7 @@ def test_batch_verify_target_sites_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine_service.ListTargetSitesResponse() # 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 @@ -7072,83 +7408,221 @@ def test_batch_verify_target_sites_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "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 = site_search_engine_service.ListTargetSitesResponse.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 - response = client.batch_verify_target_sites(request) + response = client.list_target_sites(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_verify_target_sites_rest_unset_required_fields(): +def test_list_target_sites_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_verify_target_sites._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent",))) - - -def test_fetch_domain_verification_status_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 = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + unset_fields = transport.list_target_sites._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) ) + & set(("parent",)) + ) - # 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.fetch_domain_verification_status - in client._transport._wrapped_methods - ) +def test_list_target_sites_rest_flattened(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( + # 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 = site_search_engine_service.ListTargetSitesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = site_search_engine_service.ListTargetSitesResponse.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 + + client.list_target_sites(**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/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites" + % client.transport._host, + args[1], + ) + + +def test_list_target_sites_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + 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_target_sites( + site_search_engine_service.ListTargetSitesRequest(), + parent="parent_value", + ) + + +def test_list_target_sites_rest_pager(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + 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 = ( + site_search_engine_service.ListTargetSitesResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + next_page_token="abc", + ), + site_search_engine_service.ListTargetSitesResponse( + target_sites=[], + next_page_token="def", + ), + site_search_engine_service.ListTargetSitesResponse( + target_sites=[ + site_search_engine.TargetSite(), + ], + next_page_token="ghi", + ), + site_search_engine_service.ListTargetSitesResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + site_search_engine_service.ListTargetSitesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + + pager = client.list_target_sites(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, site_search_engine.TargetSite) for i in results) + + pages = list(client.list_target_sites(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_sitemap_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 = SiteSearchEngineServiceClient( + 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.create_sitemap 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.fetch_domain_verification_status - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_sitemap] = mock_rpc request = {} - client.fetch_domain_verification_status(request) + client.create_sitemap(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_domain_verification_status(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_sitemap(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_fetch_domain_verification_status_rest_required_fields( - request_type=site_search_engine_service.FetchDomainVerificationStatusRequest, +def test_create_sitemap_rest_required_fields( + request_type=site_search_engine_service.CreateSitemapRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["site_search_engine"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7159,28 +7633,21 @@ def test_fetch_domain_verification_status_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_domain_verification_status._get_unset_required_fields(jsonified_request) + ).create_sitemap._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["siteSearchEngine"] = "site_search_engine_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_domain_verification_status._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).create_sitemap._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "siteSearchEngine" in jsonified_request - assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7189,7 +7656,7 @@ def test_fetch_domain_verification_status_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = site_search_engine_service.FetchDomainVerificationStatusResponse() + return_value = operations_pb2.Operation(name="operations/spam") # 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 @@ -7201,865 +7668,2518 @@ def test_fetch_domain_verification_status_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "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 = ( - site_search_engine_service.FetchDomainVerificationStatusResponse.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 - response = client.fetch_domain_verification_status(request) + response = client.create_sitemap(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_fetch_domain_verification_status_rest_unset_required_fields(): +def test_create_sitemap_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.fetch_domain_verification_status._get_unset_required_fields({}) - ) + unset_fields = transport.create_sitemap._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "parent", + "sitemap", ) ) - & set(("siteSearchEngine",)) ) -def test_fetch_domain_verification_status_rest_pager(transport: str = "rest"): +def test_create_sitemap_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) # 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 = ( - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - next_page_token="abc", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[], - next_page_token="def", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - ], - next_page_token="ghi", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - site_search_engine_service.FetchDomainVerificationStatusResponse.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 + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # get arguments that satisfy an http rule for this method sample_request = { - "site_search_engine": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } - pager = client.fetch_domain_verification_status(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, site_search_engine.TargetSite) for i in results) - - pages = list( - client.fetch_domain_verification_status(request=sample_request).pages + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + sitemap=site_search_engine.Sitemap(uri="uri_value"), ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + mock_args.update(sample_request) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + client.create_sitemap(**mock_args) - # It is an error to provide a credentials file and a transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # 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/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/sitemaps" + % client.transport._host, + args[1], ) - # It is an error to provide an api_key and a transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( + +def test_create_sitemap_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - 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" + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client.create_sitemap( + site_search_engine_service.CreateSitemapRequest(), + parent="parent_value", + sitemap=site_search_engine.Sitemap(uri="uri_value"), ) - # It is an error to provide scopes and a transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): + +def test_delete_sitemap_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 = SiteSearchEngineServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SiteSearchEngineServiceClient(transport=transport) - assert client.transport is transport + # Ensure method has been cached + assert client._transport.delete_sitemap 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_sitemap] = mock_rpc -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + request = {} + client.delete_sitemap(request) - transport = transports.SiteSearchEngineServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # 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() -@pytest.mark.parametrize( - "transport_class", - [ - transports.SiteSearchEngineServiceGrpcTransport, - transports.SiteSearchEngineServiceGrpcAsyncIOTransport, - transports.SiteSearchEngineServiceRestTransport, - ], -) -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() + client.delete_sitemap(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_transport_kind_grpc(): - transport = SiteSearchEngineServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" +def test_delete_sitemap_rest_required_fields( + request_type=site_search_engine_service.DeleteSitemapRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport -def test_initialize_client_w_grpc(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + request_init = {} + request_init["name"] = "" + 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) ) - assert client is not None + # verify fields with default values are dropped -# 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_site_search_engine_empty_call_grpc(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_sitemap._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_site_search_engine), "__call__" - ) as call: - call.return_value = site_search_engine.SiteSearchEngine() - client.get_site_search_engine(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.GetSiteSearchEngineRequest() + jsonified_request["name"] = "name_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_sitemap._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -# 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_create_target_site_empty_call_grpc(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_target_site), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_target_site(request=None) + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.CreateTargetSiteRequest() + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - assert args[0] == request_msg + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_sitemap(request) -# 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_batch_create_target_sites_empty_call_grpc(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_target_sites), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_create_target_sites(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.BatchCreateTargetSitesRequest() +def test_delete_sitemap_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.delete_sitemap._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -# 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_target_site_empty_call_grpc(): +def test_delete_sitemap_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_target_site), "__call__") as call: - call.return_value = site_search_engine.TargetSite() - client.get_target_site(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.GetTargetSiteRequest() + # 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 = operations_pb2.Operation(name="operations/spam") - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/sitemaps/sample4" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) -# 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_target_site_empty_call_grpc(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_target_site), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_target_site(request=None) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.UpdateTargetSiteRequest() + client.delete_sitemap(**mock_args) - assert args[0] == request_msg + # 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/v1beta/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/sitemaps/*}" + % client.transport._host, + args[1], + ) -# 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_target_site_empty_call_grpc(): +def test_delete_sitemap_rest_flattened_error(transport: str = "rest"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_target_site), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_target_site(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_sitemap( + site_search_engine_service.DeleteSitemapRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.DeleteTargetSiteRequest() - assert args[0] == request_msg +def test_fetch_sitemaps_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 = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_target_sites_empty_call_grpc(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert client._transport.fetch_sitemaps in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_target_sites), "__call__" - ) as call: - call.return_value = site_search_engine_service.ListTargetSitesResponse() - client.list_target_sites(request=None) + # 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.fetch_sitemaps] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.ListTargetSitesRequest() + request = {} + client.fetch_sitemaps(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.fetch_sitemaps(request) -# 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_enable_advanced_site_search_empty_call_grpc(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.enable_advanced_site_search), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.enable_advanced_site_search(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.EnableAdvancedSiteSearchRequest() +def test_fetch_sitemaps_rest_required_fields( + request_type=site_search_engine_service.FetchSitemapsRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport - assert args[0] == request_msg + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + # verify fields with default values are dropped -# 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_disable_advanced_site_search_empty_call_grpc(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_sitemaps._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_advanced_site_search), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.disable_advanced_site_search(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.DisableAdvancedSiteSearchRequest() + jsonified_request["parent"] = "parent_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_sitemaps._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("matcher",)) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -# 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_recrawl_uris_empty_call_grpc(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.recrawl_uris(request=None) + # Designate an appropriate value for the returned response. + return_value = site_search_engine_service.FetchSitemapsResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.RecrawlUrisRequest() + response_value = Response() + response_value.status_code = 200 - assert args[0] == request_msg + # Convert return value to protobuf type + return_value = site_search_engine_service.FetchSitemapsResponse.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 -# 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_batch_verify_target_sites_empty_call_grpc(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.fetch_sitemaps(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_verify_target_sites), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_verify_target_sites(request=None) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.BatchVerifyTargetSitesRequest() - assert args[0] == request_msg +def test_fetch_sitemaps_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + unset_fields = transport.fetch_sitemaps._get_unset_required_fields({}) + assert set(unset_fields) == (set(("matcher",)) & set(("parent",))) -# 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_fetch_domain_verification_status_empty_call_grpc(): + +def test_fetch_sitemaps_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" - ) as call: - call.return_value = ( - site_search_engine_service.FetchDomainVerificationStatusResponse() - ) - client.fetch_domain_verification_status(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.FetchDomainVerificationStatusRequest() + # 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 = site_search_engine_service.FetchSitemapsResponse() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) -def test_transport_kind_grpc_asyncio(): - transport = SiteSearchEngineServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine_service.FetchSitemapsResponse.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 + client.fetch_sitemaps(**mock_args) -def test_initialize_client_w_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # 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/v1beta/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/sitemaps:fetch" + % client.transport._host, + args[1], + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_site_search_engine_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_fetch_sitemaps_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_site_search_engine), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - site_search_engine.SiteSearchEngine( - name="name_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_sitemaps( + site_search_engine_service.FetchSitemapsRequest(), + parent="parent_value", ) - await client.get_site_search_engine(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.GetSiteSearchEngineRequest() - assert args[0] == request_msg +def test_enable_advanced_site_search_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 = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_target_site_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_target_site), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Ensure method has been cached + assert ( + client._transport.enable_advanced_site_search + in client._transport._wrapped_methods ) - await client.create_target_site(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.CreateTargetSiteRequest() + # 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.enable_advanced_site_search + ] = mock_rpc - assert args[0] == request_msg + request = {} + client.enable_advanced_site_search(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_batch_create_target_sites_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_target_sites), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.batch_create_target_sites(request=None) + client.enable_advanced_site_search(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.BatchCreateTargetSitesRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +def test_enable_advanced_site_search_rest_required_fields( + request_type=site_search_engine_service.EnableAdvancedSiteSearchRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_target_site_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["site_search_engine"] = "" + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_target_site), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - site_search_engine.TargetSite( - name="name_value", - provided_uri_pattern="provided_uri_pattern_value", - type_=site_search_engine.TargetSite.Type.INCLUDE, - exact_match=True, - generated_uri_pattern="generated_uri_pattern_value", - root_domain_uri="root_domain_uri_value", - indexing_status=site_search_engine.TargetSite.IndexingStatus.PENDING, - ) - ) - await client.get_target_site(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.GetTargetSiteRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_advanced_site_search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + jsonified_request["siteSearchEngine"] = "site_search_engine_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_target_site_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_advanced_site_search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "siteSearchEngine" in jsonified_request + assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" + + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_target_site), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.update_target_site(request=None) + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.UpdateTargetSiteRequest() + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - assert args[0] == request_msg + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.enable_advanced_site_search(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_target_site_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_target_site), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.delete_target_site(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.DeleteTargetSiteRequest() +def test_enable_advanced_site_search_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - assert args[0] == request_msg + unset_fields = transport.enable_advanced_site_search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_target_sites_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) +def test_disable_advanced_site_search_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 = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_target_sites), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - site_search_engine_service.ListTargetSitesResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) + # 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.disable_advanced_site_search + in client._transport._wrapped_methods ) - await client.list_target_sites(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.ListTargetSitesRequest() + # 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.disable_advanced_site_search + ] = mock_rpc - assert args[0] == request_msg + request = {} + client.disable_advanced_site_search(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() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_enable_advanced_site_search_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client.disable_advanced_site_search(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_disable_advanced_site_search_rest_required_fields( + request_type=site_search_engine_service.DisableAdvancedSiteSearchRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport + + request_init = {} + request_init["site_search_engine"] = "" + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.enable_advanced_site_search), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.enable_advanced_site_search(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.EnableAdvancedSiteSearchRequest() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).disable_advanced_site_search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - assert args[0] == request_msg + # verify required fields with default values are now present + jsonified_request["siteSearchEngine"] = "site_search_engine_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_disable_advanced_site_search_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).disable_advanced_site_search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "siteSearchEngine" in jsonified_request + assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" + + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_advanced_site_search), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.disable_advanced_site_search(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_disable_advanced_site_search_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.disable_advanced_site_search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) + + +def test_recrawl_uris_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 = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - await client.disable_advanced_site_search(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.DisableAdvancedSiteSearchRequest() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - assert args[0] == request_msg + # Ensure method has been cached + assert client._transport.recrawl_uris 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.recrawl_uris] = mock_rpc + request = {} + client.recrawl_uris(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_recrawl_uris_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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.recrawl_uris(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_recrawl_uris_rest_required_fields( + request_type=site_search_engine_service.RecrawlUrisRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport + + request_init = {} + request_init["site_search_engine"] = "" + request_init["uris"] = "" + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).recrawl_uris._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["siteSearchEngine"] = "site_search_engine_value" + jsonified_request["uris"] = "uris_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).recrawl_uris._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "siteSearchEngine" in jsonified_request + assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" + assert "uris" in jsonified_request + assert jsonified_request["uris"] == "uris_value" + + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.recrawl_uris(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_recrawl_uris_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.recrawl_uris._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "siteSearchEngine", + "uris", + ) + ) + ) + + +def test_batch_verify_target_sites_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 = SiteSearchEngineServiceClient( + 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.batch_verify_target_sites + 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.batch_verify_target_sites + ] = mock_rpc + + request = {} + client.batch_verify_target_sites(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.batch_verify_target_sites(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_batch_verify_target_sites_rest_required_fields( + request_type=site_search_engine_service.BatchVerifyTargetSitesRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_verify_target_sites._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_verify_target_sites._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.batch_verify_target_sites(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_verify_target_sites_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_verify_target_sites._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +def test_fetch_domain_verification_status_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 = SiteSearchEngineServiceClient( + 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.fetch_domain_verification_status + 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.fetch_domain_verification_status + ] = mock_rpc + + request = {} + client.fetch_domain_verification_status(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_domain_verification_status(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_fetch_domain_verification_status_rest_required_fields( + request_type=site_search_engine_service.FetchDomainVerificationStatusRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport + + request_init = {} + request_init["site_search_engine"] = "" + 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() + ).fetch_domain_verification_status._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["siteSearchEngine"] = "site_search_engine_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_domain_verification_status._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "siteSearchEngine" in jsonified_request + assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" + + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = site_search_engine_service.FetchDomainVerificationStatusResponse() + # 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 = ( + site_search_engine_service.FetchDomainVerificationStatusResponse.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 + + response = client.fetch_domain_verification_status(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_fetch_domain_verification_status_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.fetch_domain_verification_status._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("siteSearchEngine",)) + ) + + +def test_fetch_domain_verification_status_rest_pager(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + 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 = ( + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + next_page_token="abc", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[], + next_page_token="def", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + ], + next_page_token="ghi", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + site_search_engine_service.FetchDomainVerificationStatusResponse.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 = { + "site_search_engine": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" + } + + pager = client.fetch_domain_verification_status(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, site_search_engine.TargetSite) for i in results) + + pages = list( + client.fetch_domain_verification_status(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + 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 = SiteSearchEngineServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SiteSearchEngineServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SiteSearchEngineServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SiteSearchEngineServiceGrpcTransport, + transports.SiteSearchEngineServiceGrpcAsyncIOTransport, + transports.SiteSearchEngineServiceRestTransport, + ], +) +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_grpc(): + transport = SiteSearchEngineServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + 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_site_search_engine_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_site_search_engine), "__call__" + ) as call: + call.return_value = site_search_engine.SiteSearchEngine() + client.get_site_search_engine(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.GetSiteSearchEngineRequest() + + 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_create_target_site_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_target_site), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_target_site(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.CreateTargetSiteRequest() + + 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_batch_create_target_sites_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_target_sites), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.batch_create_target_sites(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.BatchCreateTargetSitesRequest() + + 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_target_site_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_target_site), "__call__") as call: + call.return_value = site_search_engine.TargetSite() + client.get_target_site(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.GetTargetSiteRequest() + + 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_target_site_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_target_site), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_target_site(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.UpdateTargetSiteRequest() + + 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_target_site_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_target_site), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_target_site(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.DeleteTargetSiteRequest() + + 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_target_sites_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_target_sites), "__call__" + ) as call: + call.return_value = site_search_engine_service.ListTargetSitesResponse() + client.list_target_sites(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.ListTargetSitesRequest() + + 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_create_sitemap_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_sitemap(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.CreateSitemapRequest() + + 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_sitemap_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_sitemap(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.DeleteSitemapRequest() + + 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_fetch_sitemaps_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: + call.return_value = site_search_engine_service.FetchSitemapsResponse() + client.fetch_sitemaps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.FetchSitemapsRequest() + + 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_enable_advanced_site_search_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_advanced_site_search), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.enable_advanced_site_search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.EnableAdvancedSiteSearchRequest() + + 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_disable_advanced_site_search_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_advanced_site_search), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.disable_advanced_site_search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.DisableAdvancedSiteSearchRequest() + + 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_recrawl_uris_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.recrawl_uris(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.RecrawlUrisRequest() + + 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_batch_verify_target_sites_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_verify_target_sites), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.batch_verify_target_sites(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.BatchVerifyTargetSitesRequest() + + 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_fetch_domain_verification_status_empty_call_grpc(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + call.return_value = ( + site_search_engine_service.FetchDomainVerificationStatusResponse() + ) + client.fetch_domain_verification_status(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.FetchDomainVerificationStatusRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SiteSearchEngineServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + 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. +@pytest.mark.asyncio +async def test_get_site_search_engine_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_site_search_engine), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine.SiteSearchEngine( + name="name_value", + ) + ) + await client.get_site_search_engine(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.GetSiteSearchEngineRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_target_site_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_target_site), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_target_site(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.CreateTargetSiteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_create_target_sites_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_target_sites), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.batch_create_target_sites(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.BatchCreateTargetSitesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_target_site_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_target_site), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine.TargetSite( + name="name_value", + provided_uri_pattern="provided_uri_pattern_value", + type_=site_search_engine.TargetSite.Type.INCLUDE, + exact_match=True, + generated_uri_pattern="generated_uri_pattern_value", + root_domain_uri="root_domain_uri_value", + indexing_status=site_search_engine.TargetSite.IndexingStatus.PENDING, + ) + ) + await client.get_target_site(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.GetTargetSiteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_target_site_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_target_site), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_target_site(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.UpdateTargetSiteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_target_site_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_target_site), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_target_site(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.DeleteTargetSiteRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_target_sites_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_target_sites), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.ListTargetSitesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + await client.list_target_sites(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.ListTargetSitesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_sitemap_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_sitemap(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.CreateSitemapRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_sitemap_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_sitemap(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.DeleteSitemapRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_sitemaps_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.FetchSitemapsResponse() + ) + await client.fetch_sitemaps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.FetchSitemapsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_enable_advanced_site_search_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_advanced_site_search), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.enable_advanced_site_search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.EnableAdvancedSiteSearchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_disable_advanced_site_search_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_advanced_site_search), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.disable_advanced_site_search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.DisableAdvancedSiteSearchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_recrawl_uris_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.recrawl_uris), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.recrawl_uris(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.RecrawlUrisRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_verify_target_sites_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_verify_target_sites), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.batch_verify_target_sites(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.BatchVerifyTargetSitesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_domain_verification_status_empty_call_grpc_asyncio(): + client = SiteSearchEngineServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_domain_verification_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.FetchDomainVerificationStatusResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + await client.fetch_domain_verification_status(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.FetchDomainVerificationStatusRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SiteSearchEngineServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_site_search_engine_rest_bad_request( + request_type=site_search_engine_service.GetSiteSearchEngineRequest, +): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + 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 + client.get_site_search_engine(request) + + +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.GetSiteSearchEngineRequest, + dict, + ], +) +def test_get_site_search_engine_rest_call_success(request_type): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + 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 = site_search_engine.SiteSearchEngine( + 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 = site_search_engine.SiteSearchEngine.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 + response = client.get_site_search_engine(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, site_search_engine.SiteSearchEngine) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_site_search_engine_rest_interceptors(null_interceptor): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SiteSearchEngineServiceRestInterceptor(), + ) + client = SiteSearchEngineServiceClient(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.SiteSearchEngineServiceRestInterceptor, "post_get_site_search_engine" + ) as post, mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, "pre_get_site_search_engine" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = site_search_engine_service.GetSiteSearchEngineRequest.pb( + site_search_engine_service.GetSiteSearchEngineRequest() + ) + 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 + return_value = site_search_engine.SiteSearchEngine.to_json( + site_search_engine.SiteSearchEngine() + ) + req.return_value.content = return_value + + request = site_search_engine_service.GetSiteSearchEngineRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = site_search_engine.SiteSearchEngine() + + client.get_site_search_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_target_site_rest_bad_request( + request_type=site_search_engine_service.CreateTargetSiteRequest, +): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + 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 + client.create_target_site(request) + + +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.CreateTargetSiteRequest, + dict, + ], +) +def test_create_target_site_rest_call_success(request_type): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request_init["target_site"] = { + "name": "name_value", + "provided_uri_pattern": "provided_uri_pattern_value", + "type_": 1, + "exact_match": True, + "generated_uri_pattern": "generated_uri_pattern_value", + "root_domain_uri": "root_domain_uri_value", + "site_verification_info": { + "site_verification_state": 1, + "verify_time": {"seconds": 751, "nanos": 543}, + }, + "indexing_status": 1, + "update_time": {}, + "failure_reason": {"quota_failure": {"total_required_quota": 2157}}, + } + # 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 = site_search_engine_service.CreateTargetSiteRequest.meta.fields[ + "target_site" + ] + + 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["target_site"].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["target_site"][field])): + del request_init["target_site"][field][i][subfield] + else: + del request_init["target_site"][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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_target_site(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_target_site_rest_interceptors(null_interceptor): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SiteSearchEngineServiceRestInterceptor(), + ) + client = SiteSearchEngineServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, "post_create_target_site" + ) as post, mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, "pre_create_target_site" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = site_search_engine_service.CreateTargetSiteRequest.pb( + site_search_engine_service.CreateTargetSiteRequest() + ) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = site_search_engine_service.CreateTargetSiteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_target_site( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - await client.recrawl_uris(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.RecrawlUrisRequest() + pre.assert_called_once() + post.assert_called_once() - assert args[0] == request_msg +def test_batch_create_target_sites_rest_bad_request( + request_type=site_search_engine_service.BatchCreateTargetSitesRequest, +): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request = request_type(**request_init) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_batch_verify_target_sites_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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 + client.batch_create_target_sites(request) + + +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.BatchCreateTargetSitesRequest, + dict, + ], +) +def test_batch_create_target_sites_rest_call_success(request_type): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.batch_verify_target_sites), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.batch_verify_target_sites(request=None) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request = request_type(**request_init) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.BatchVerifyTargetSitesRequest() + # 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 = operations_pb2.Operation(name="operations/spam") - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_create_target_sites(request) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_fetch_domain_verification_status_empty_call_grpc_asyncio(): - client = SiteSearchEngineServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_target_sites_rest_interceptors(null_interceptor): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SiteSearchEngineServiceRestInterceptor(), ) + client = SiteSearchEngineServiceClient(transport=transport) - # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.fetch_domain_verification_status), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - site_search_engine_service.FetchDomainVerificationStatusResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, + "post_batch_create_target_sites", + ) as post, mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, + "pre_batch_create_target_sites", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = site_search_engine_service.BatchCreateTargetSitesRequest.pb( + site_search_engine_service.BatchCreateTargetSitesRequest() ) - await client.fetch_domain_verification_status(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = site_search_engine_service.FetchDomainVerificationStatusRequest() + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - assert args[0] == request_msg + request = site_search_engine_service.BatchCreateTargetSitesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + client.batch_create_target_sites( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = SiteSearchEngineServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() -def test_get_site_search_engine_rest_bad_request( - request_type=site_search_engine_service.GetSiteSearchEngineRequest, +def test_get_target_site_rest_bad_request( + request_type=site_search_engine_service.GetTargetSiteRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" } request = request_type(**request_init) @@ -8074,32 +10194,38 @@ def test_get_site_search_engine_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_site_search_engine(request) + client.get_target_site(request) @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.GetSiteSearchEngineRequest, + site_search_engine_service.GetTargetSiteRequest, dict, ], ) -def test_get_site_search_engine_rest_call_success(request_type): +def test_get_target_site_rest_call_success(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" } 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 = site_search_engine.SiteSearchEngine( + return_value = site_search_engine.TargetSite( name="name_value", + provided_uri_pattern="provided_uri_pattern_value", + type_=site_search_engine.TargetSite.Type.INCLUDE, + exact_match=True, + generated_uri_pattern="generated_uri_pattern_value", + root_domain_uri="root_domain_uri_value", + indexing_status=site_search_engine.TargetSite.IndexingStatus.PENDING, ) # Wrap the value into a proper Response obj @@ -8107,19 +10233,27 @@ def test_get_site_search_engine_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = site_search_engine.SiteSearchEngine.pb(return_value) + return_value = site_search_engine.TargetSite.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 - response = client.get_site_search_engine(request) + response = client.get_target_site(request) # Establish that the response is the type that we expect. - assert isinstance(response, site_search_engine.SiteSearchEngine) + assert isinstance(response, site_search_engine.TargetSite) assert response.name == "name_value" + assert response.provided_uri_pattern == "provided_uri_pattern_value" + assert response.type_ == site_search_engine.TargetSite.Type.INCLUDE + assert response.exact_match is True + assert response.generated_uri_pattern == "generated_uri_pattern_value" + assert response.root_domain_uri == "root_domain_uri_value" + assert ( + response.indexing_status == site_search_engine.TargetSite.IndexingStatus.PENDING + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_site_search_engine_rest_interceptors(null_interceptor): +def test_get_target_site_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8133,14 +10267,14 @@ def test_get_site_search_engine_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_get_site_search_engine" + transports.SiteSearchEngineServiceRestInterceptor, "post_get_target_site" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_get_site_search_engine" + transports.SiteSearchEngineServiceRestInterceptor, "pre_get_target_site" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.GetSiteSearchEngineRequest.pb( - site_search_engine_service.GetSiteSearchEngineRequest() + pb_message = site_search_engine_service.GetTargetSiteRequest.pb( + site_search_engine_service.GetTargetSiteRequest() ) transcode.return_value = { "method": "post", @@ -8151,20 +10285,20 @@ def test_get_site_search_engine_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = site_search_engine.SiteSearchEngine.to_json( - site_search_engine.SiteSearchEngine() + return_value = site_search_engine.TargetSite.to_json( + site_search_engine.TargetSite() ) req.return_value.content = return_value - request = site_search_engine_service.GetSiteSearchEngineRequest() + request = site_search_engine_service.GetTargetSiteRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = site_search_engine.SiteSearchEngine() + post.return_value = site_search_engine.TargetSite() - client.get_site_search_engine( + client.get_target_site( request, metadata=[ ("key", "val"), @@ -8176,15 +10310,17 @@ def test_get_site_search_engine_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_target_site_rest_bad_request( - request_type=site_search_engine_service.CreateTargetSiteRequest, +def test_update_target_site_rest_bad_request( + request_type=site_search_engine_service.UpdateTargetSiteRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "target_site": { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + } } request = request_type(**request_init) @@ -8199,27 +10335,29 @@ def test_create_target_site_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.create_target_site(request) + client.update_target_site(request) @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.CreateTargetSiteRequest, + site_search_engine_service.UpdateTargetSiteRequest, dict, ], ) -def test_create_target_site_rest_call_success(request_type): +def test_update_target_site_rest_call_success(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "target_site": { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + } } request_init["target_site"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4", "provided_uri_pattern": "provided_uri_pattern_value", "type_": 1, "exact_match": True, @@ -8238,7 +10376,7 @@ def test_create_target_site_rest_call_success(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = site_search_engine_service.CreateTargetSiteRequest.meta.fields[ + test_field = site_search_engine_service.UpdateTargetSiteRequest.meta.fields[ "target_site" ] @@ -8315,14 +10453,14 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_target_site(request) + response = client.update_target_site(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_target_site_rest_interceptors(null_interceptor): +def test_update_target_site_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8338,14 +10476,14 @@ def test_create_target_site_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_create_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "post_update_target_site" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_create_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "pre_update_target_site" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.CreateTargetSiteRequest.pb( - site_search_engine_service.CreateTargetSiteRequest() + pb_message = site_search_engine_service.UpdateTargetSiteRequest.pb( + site_search_engine_service.UpdateTargetSiteRequest() ) transcode.return_value = { "method": "post", @@ -8359,7 +10497,7 @@ def test_create_target_site_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = site_search_engine_service.CreateTargetSiteRequest() + request = site_search_engine_service.UpdateTargetSiteRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8367,7 +10505,7 @@ def test_create_target_site_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_target_site( + client.update_target_site( request, metadata=[ ("key", "val"), @@ -8379,15 +10517,15 @@ def test_create_target_site_rest_interceptors(null_interceptor): post.assert_called_once() -def test_batch_create_target_sites_rest_bad_request( - request_type=site_search_engine_service.BatchCreateTargetSitesRequest, +def test_delete_target_site_rest_bad_request( + request_type=site_search_engine_service.DeleteTargetSiteRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" } request = request_type(**request_init) @@ -8402,24 +10540,24 @@ def test_batch_create_target_sites_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.batch_create_target_sites(request) + client.delete_target_site(request) @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.BatchCreateTargetSitesRequest, + site_search_engine_service.DeleteTargetSiteRequest, dict, ], ) -def test_batch_create_target_sites_rest_call_success(request_type): +def test_delete_target_site_rest_call_success(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" } request = request_type(**request_init) @@ -8434,14 +10572,14 @@ def test_batch_create_target_sites_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_target_sites(request) + response = client.delete_target_site(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_target_sites_rest_interceptors(null_interceptor): +def test_delete_target_site_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8457,16 +10595,14 @@ def test_batch_create_target_sites_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, - "post_batch_create_target_sites", + transports.SiteSearchEngineServiceRestInterceptor, "post_delete_target_site" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, - "pre_batch_create_target_sites", + transports.SiteSearchEngineServiceRestInterceptor, "pre_delete_target_site" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.BatchCreateTargetSitesRequest.pb( - site_search_engine_service.BatchCreateTargetSitesRequest() + pb_message = site_search_engine_service.DeleteTargetSiteRequest.pb( + site_search_engine_service.DeleteTargetSiteRequest() ) transcode.return_value = { "method": "post", @@ -8480,7 +10616,7 @@ def test_batch_create_target_sites_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = site_search_engine_service.BatchCreateTargetSitesRequest() + request = site_search_engine_service.DeleteTargetSiteRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8488,7 +10624,7 @@ def test_batch_create_target_sites_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.batch_create_target_sites( + client.delete_target_site( request, metadata=[ ("key", "val"), @@ -8500,15 +10636,15 @@ def test_batch_create_target_sites_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_target_site_rest_bad_request( - request_type=site_search_engine_service.GetTargetSiteRequest, +def test_list_target_sites_rest_bad_request( + request_type=site_search_engine_service.ListTargetSitesRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } request = request_type(**request_init) @@ -8523,38 +10659,33 @@ def test_get_target_site_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_target_site(request) + client.list_target_sites(request) @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.GetTargetSiteRequest, + site_search_engine_service.ListTargetSitesRequest, dict, ], ) -def test_get_target_site_rest_call_success(request_type): +def test_list_target_sites_rest_call_success(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } 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 = site_search_engine.TargetSite( - name="name_value", - provided_uri_pattern="provided_uri_pattern_value", - type_=site_search_engine.TargetSite.Type.INCLUDE, - exact_match=True, - generated_uri_pattern="generated_uri_pattern_value", - root_domain_uri="root_domain_uri_value", - indexing_status=site_search_engine.TargetSite.IndexingStatus.PENDING, + return_value = site_search_engine_service.ListTargetSitesResponse( + next_page_token="next_page_token_value", + total_size=1086, ) # Wrap the value into a proper Response obj @@ -8562,27 +10693,22 @@ def test_get_target_site_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = site_search_engine.TargetSite.pb(return_value) + return_value = site_search_engine_service.ListTargetSitesResponse.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 - response = client.get_target_site(request) + response = client.list_target_sites(request) # Establish that the response is the type that we expect. - assert isinstance(response, site_search_engine.TargetSite) - assert response.name == "name_value" - assert response.provided_uri_pattern == "provided_uri_pattern_value" - assert response.type_ == site_search_engine.TargetSite.Type.INCLUDE - assert response.exact_match is True - assert response.generated_uri_pattern == "generated_uri_pattern_value" - assert response.root_domain_uri == "root_domain_uri_value" - assert ( - response.indexing_status == site_search_engine.TargetSite.IndexingStatus.PENDING - ) + assert isinstance(response, pagers.ListTargetSitesPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_target_site_rest_interceptors(null_interceptor): +def test_list_target_sites_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8596,14 +10722,14 @@ def test_get_target_site_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_get_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "post_list_target_sites" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_get_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "pre_list_target_sites" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.GetTargetSiteRequest.pb( - site_search_engine_service.GetTargetSiteRequest() + pb_message = site_search_engine_service.ListTargetSitesRequest.pb( + site_search_engine_service.ListTargetSitesRequest() ) transcode.return_value = { "method": "post", @@ -8614,20 +10740,20 @@ def test_get_target_site_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = site_search_engine.TargetSite.to_json( - site_search_engine.TargetSite() + return_value = site_search_engine_service.ListTargetSitesResponse.to_json( + site_search_engine_service.ListTargetSitesResponse() ) req.return_value.content = return_value - request = site_search_engine_service.GetTargetSiteRequest() + request = site_search_engine_service.ListTargetSitesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = site_search_engine.TargetSite() + post.return_value = site_search_engine_service.ListTargetSitesResponse() - client.get_target_site( + client.list_target_sites( request, metadata=[ ("key", "val"), @@ -8639,17 +10765,15 @@ def test_get_target_site_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_target_site_rest_bad_request( - request_type=site_search_engine_service.UpdateTargetSiteRequest, +def test_create_sitemap_rest_bad_request( + request_type=site_search_engine_service.CreateSitemapRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "target_site": { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } request = request_type(**request_init) @@ -8664,50 +10788,36 @@ def test_update_target_site_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.update_target_site(request) + client.create_sitemap(request) @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.UpdateTargetSiteRequest, + site_search_engine_service.CreateSitemapRequest, dict, ], ) -def test_update_target_site_rest_call_success(request_type): +def test_create_sitemap_rest_call_success(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "target_site": { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } - request_init["target_site"] = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4", - "provided_uri_pattern": "provided_uri_pattern_value", - "type_": 1, - "exact_match": True, - "generated_uri_pattern": "generated_uri_pattern_value", - "root_domain_uri": "root_domain_uri_value", - "site_verification_info": { - "site_verification_state": 1, - "verify_time": {"seconds": 751, "nanos": 543}, - }, - "indexing_status": 1, - "update_time": {}, - "failure_reason": {"quota_failure": {"total_required_quota": 2157}}, + request_init["sitemap"] = { + "uri": "uri_value", + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, } # 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 = site_search_engine_service.UpdateTargetSiteRequest.meta.fields[ - "target_site" - ] + test_field = site_search_engine_service.CreateSitemapRequest.meta.fields["sitemap"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -8735,7 +10845,7 @@ def get_message_fields(field): # 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["target_site"].items(): # pragma: NO COVER + for field, value in request_init["sitemap"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -8765,10 +10875,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["target_site"][field])): - del request_init["target_site"][field][i][subfield] + for i in range(0, len(request_init["sitemap"][field])): + del request_init["sitemap"][field][i][subfield] else: - del request_init["target_site"][field][subfield] + del request_init["sitemap"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -8782,14 +10892,14 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_target_site(request) + response = client.create_sitemap(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_target_site_rest_interceptors(null_interceptor): +def test_create_sitemap_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8805,14 +10915,14 @@ def test_update_target_site_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_update_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "post_create_sitemap" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_update_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "pre_create_sitemap" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.UpdateTargetSiteRequest.pb( - site_search_engine_service.UpdateTargetSiteRequest() + pb_message = site_search_engine_service.CreateSitemapRequest.pb( + site_search_engine_service.CreateSitemapRequest() ) transcode.return_value = { "method": "post", @@ -8826,7 +10936,7 @@ def test_update_target_site_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = site_search_engine_service.UpdateTargetSiteRequest() + request = site_search_engine_service.CreateSitemapRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8834,7 +10944,7 @@ def test_update_target_site_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_target_site( + client.create_sitemap( request, metadata=[ ("key", "val"), @@ -8846,15 +10956,15 @@ def test_update_target_site_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_target_site_rest_bad_request( - request_type=site_search_engine_service.DeleteTargetSiteRequest, +def test_delete_sitemap_rest_bad_request( + request_type=site_search_engine_service.DeleteSitemapRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/sitemaps/sample4" } request = request_type(**request_init) @@ -8869,24 +10979,24 @@ def test_delete_target_site_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.delete_target_site(request) + client.delete_sitemap(request) @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.DeleteTargetSiteRequest, + site_search_engine_service.DeleteSitemapRequest, dict, ], ) -def test_delete_target_site_rest_call_success(request_type): +def test_delete_sitemap_rest_call_success(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/sitemaps/sample4" } request = request_type(**request_init) @@ -8901,14 +11011,14 @@ def test_delete_target_site_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_target_site(request) + response = client.delete_sitemap(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_target_site_rest_interceptors(null_interceptor): +def test_delete_sitemap_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8924,14 +11034,14 @@ def test_delete_target_site_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_delete_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "post_delete_sitemap" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_delete_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "pre_delete_sitemap" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.DeleteTargetSiteRequest.pb( - site_search_engine_service.DeleteTargetSiteRequest() + pb_message = site_search_engine_service.DeleteSitemapRequest.pb( + site_search_engine_service.DeleteSitemapRequest() ) transcode.return_value = { "method": "post", @@ -8945,7 +11055,7 @@ def test_delete_target_site_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = site_search_engine_service.DeleteTargetSiteRequest() + request = site_search_engine_service.DeleteSitemapRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8953,7 +11063,7 @@ def test_delete_target_site_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_target_site( + client.delete_sitemap( request, metadata=[ ("key", "val"), @@ -8965,8 +11075,8 @@ def test_delete_target_site_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_target_sites_rest_bad_request( - request_type=site_search_engine_service.ListTargetSitesRequest, +def test_fetch_sitemaps_rest_bad_request( + request_type=site_search_engine_service.FetchSitemapsRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -8988,17 +11098,17 @@ def test_list_target_sites_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_target_sites(request) + client.fetch_sitemaps(request) @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.ListTargetSitesRequest, + site_search_engine_service.FetchSitemapsRequest, dict, ], ) -def test_list_target_sites_rest_call_success(request_type): +def test_fetch_sitemaps_rest_call_success(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9012,32 +11122,25 @@ def test_list_target_sites_rest_call_success(request_type): # 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 = site_search_engine_service.ListTargetSitesResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) + return_value = site_search_engine_service.FetchSitemapsResponse() # 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 = site_search_engine_service.ListTargetSitesResponse.pb( - return_value - ) + return_value = site_search_engine_service.FetchSitemapsResponse.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 - response = client.list_target_sites(request) + response = client.fetch_sitemaps(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTargetSitesPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert isinstance(response, site_search_engine_service.FetchSitemapsResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_target_sites_rest_interceptors(null_interceptor): +def test_fetch_sitemaps_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9051,14 +11154,14 @@ def test_list_target_sites_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_list_target_sites" + transports.SiteSearchEngineServiceRestInterceptor, "post_fetch_sitemaps" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_list_target_sites" + transports.SiteSearchEngineServiceRestInterceptor, "pre_fetch_sitemaps" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.ListTargetSitesRequest.pb( - site_search_engine_service.ListTargetSitesRequest() + pb_message = site_search_engine_service.FetchSitemapsRequest.pb( + site_search_engine_service.FetchSitemapsRequest() ) transcode.return_value = { "method": "post", @@ -9069,20 +11172,20 @@ def test_list_target_sites_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = site_search_engine_service.ListTargetSitesResponse.to_json( - site_search_engine_service.ListTargetSitesResponse() + return_value = site_search_engine_service.FetchSitemapsResponse.to_json( + site_search_engine_service.FetchSitemapsResponse() ) req.return_value.content = return_value - request = site_search_engine_service.ListTargetSitesRequest() + request = site_search_engine_service.FetchSitemapsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = site_search_engine_service.ListTargetSitesResponse() + post.return_value = site_search_engine_service.FetchSitemapsResponse() - client.list_target_sites( + client.fetch_sitemaps( request, metadata=[ ("key", "val"), @@ -10067,6 +12170,66 @@ def test_list_target_sites_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_create_sitemap_empty_call_rest(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sitemap), "__call__") as call: + client.create_sitemap(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.CreateSitemapRequest() + + 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_sitemap_empty_call_rest(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sitemap), "__call__") as call: + client.delete_sitemap(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.DeleteSitemapRequest() + + 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_fetch_sitemaps_empty_call_rest(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_sitemaps), "__call__") as call: + client.fetch_sitemaps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = site_search_engine_service.FetchSitemapsRequest() + + 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_enable_advanced_site_search_empty_call_rest(): @@ -10232,6 +12395,9 @@ def test_site_search_engine_service_base_transport(): "update_target_site", "delete_target_site", "list_target_sites", + "create_sitemap", + "delete_sitemap", + "fetch_sitemaps", "enable_advanced_site_search", "disable_advanced_site_search", "recrawl_uris", @@ -10528,6 +12694,15 @@ def test_site_search_engine_service_client_transport_session_collision(transport session1 = client1.transport.list_target_sites._session session2 = client2.transport.list_target_sites._session assert session1 != session2 + session1 = client1.transport.create_sitemap._session + session2 = client2.transport.create_sitemap._session + assert session1 != session2 + session1 = client1.transport.delete_sitemap._session + session2 = client2.transport.delete_sitemap._session + assert session1 != session2 + session1 = client1.transport.fetch_sitemaps._session + session2 = client2.transport.fetch_sitemaps._session + assert session1 != session2 session1 = client1.transport.enable_advanced_site_search._session session2 = client2.transport.enable_advanced_site_search._session assert session1 != session2 @@ -10705,10 +12880,41 @@ def test_site_search_engine_service_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_site_search_engine_path(): +def test_sitemap_path(): project = "squid" location = "clam" data_store = "whelk" + sitemap = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine/sitemaps/{sitemap}".format( + project=project, + location=location, + data_store=data_store, + sitemap=sitemap, + ) + actual = SiteSearchEngineServiceClient.sitemap_path( + project, location, data_store, sitemap + ) + assert expected == actual + + +def test_parse_sitemap_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "sitemap": "mussel", + } + path = SiteSearchEngineServiceClient.sitemap_path(**expected) + + # Check that the path construction is reversible. + actual = SiteSearchEngineServiceClient.parse_sitemap_path(path) + assert expected == actual + + +def test_site_search_engine_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" expected = "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine".format( project=project, location=location, @@ -10722,9 +12928,9 @@ def test_site_search_engine_path(): def test_parse_site_search_engine_path(): expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", + "project": "abalone", + "location": "squid", + "data_store": "clam", } path = SiteSearchEngineServiceClient.site_search_engine_path(**expected) @@ -10734,10 +12940,10 @@ def test_parse_site_search_engine_path(): def test_target_site_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - target_site = "nautilus" + project = "whelk" + location = "octopus" + data_store = "oyster" + target_site = "nudibranch" expected = "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine/targetSites/{target_site}".format( project=project, location=location, @@ -10752,10 +12958,10 @@ def test_target_site_path(): def test_parse_target_site_path(): expected = { - "project": "scallop", - "location": "abalone", - "data_store": "squid", - "target_site": "clam", + "project": "cuttlefish", + "location": "mussel", + "data_store": "winkle", + "target_site": "nautilus", } path = SiteSearchEngineServiceClient.target_site_path(**expected) @@ -10765,7 +12971,7 @@ def test_parse_target_site_path(): def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -10775,7 +12981,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "abalone", } path = SiteSearchEngineServiceClient.common_billing_account_path(**expected) @@ -10785,7 +12991,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -10795,7 +13001,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "clam", } path = SiteSearchEngineServiceClient.common_folder_path(**expected) @@ -10805,7 +13011,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -10815,7 +13021,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "octopus", } path = SiteSearchEngineServiceClient.common_organization_path(**expected) @@ -10825,7 +13031,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -10835,7 +13041,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "nudibranch", } path = SiteSearchEngineServiceClient.common_project_path(**expected) @@ -10845,8 +13051,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -10857,8 +13063,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "winkle", + "location": "nautilus", } path = SiteSearchEngineServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py index 5df6cc8eaa97..a4879b1a5127 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py @@ -3208,6 +3208,7 @@ def test_write_user_event_rest_call_success(request_type): "display_name": "display_name_value", "panel_position": 1508, "total_panels": 1286, + "documents": {}, }, "search_info": { "search_query": "search_query_value", @@ -3233,6 +3234,7 @@ def test_write_user_event_rest_call_success(request_type): "media_progress_duration": {"seconds": 751, "nanos": 543}, "media_progress_percentage": 0.2641, }, + "panels": {}, } # 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-dms/CHANGELOG.md b/packages/google-cloud-dms/CHANGELOG.md index d3179b411dfd..256064af7c9e 100644 --- a/packages/google-cloud-dms/CHANGELOG.md +++ b/packages/google-cloud-dms/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dms-v1.10.0...google-cloud-dms-v1.10.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([59c4287](https://github.com/googleapis/google-cloud-python/commit/59c42878386ee08d1717b73e47d33d76cfb38ba0)) + ## [1.10.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dms-v1.9.5...google-cloud-dms-v1.10.0) (2024-10-24) diff --git a/packages/google-cloud-dms/google/cloud/clouddms/gapic_version.py b/packages/google-cloud-dms/google/cloud/clouddms/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-dms/google/cloud/clouddms/gapic_version.py +++ b/packages/google-cloud-dms/google/cloud/clouddms/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-dms/google/cloud/clouddms_v1/gapic_version.py b/packages/google-cloud-dms/google/cloud/clouddms_v1/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-dms/google/cloud/clouddms_v1/gapic_version.py +++ b/packages/google-cloud-dms/google/cloud/clouddms_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-dms/google/cloud/clouddms_v1/services/data_migration_service/client.py b/packages/google-cloud-dms/google/cloud/clouddms_v1/services/data_migration_service/client.py index 9b1cf5ec2627..03c7c8c2bdbd 100644 --- a/packages/google-cloud-dms/google/cloud/clouddms_v1/services/data_migration_service/client.py +++ b/packages/google-cloud-dms/google/cloud/clouddms_v1/services/data_migration_service/client.py @@ -584,36 +584,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DataMigrationServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -623,13 +593,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or DataMigrationServiceClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-dms/samples/generated_samples/snippet_metadata_google.cloud.clouddms.v1.json b/packages/google-cloud-dms/samples/generated_samples/snippet_metadata_google.cloud.clouddms.v1.json index d62ad5fe309e..08f2b744b357 100644 --- a/packages/google-cloud-dms/samples/generated_samples/snippet_metadata_google.cloud.clouddms.v1.json +++ b/packages/google-cloud-dms/samples/generated_samples/snippet_metadata_google.cloud.clouddms.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dms", - "version": "1.10.0" + "version": "1.10.1" }, "snippets": [ { diff --git a/packages/google-cloud-dms/tests/unit/gapic/clouddms_v1/test_data_migration_service.py b/packages/google-cloud-dms/tests/unit/gapic/clouddms_v1/test_data_migration_service.py index 9f888c13d551..2bfff7d057f1 100644 --- a/packages/google-cloud-dms/tests/unit/gapic/clouddms_v1/test_data_migration_service.py +++ b/packages/google-cloud-dms/tests/unit/gapic/clouddms_v1/test_data_migration_service.py @@ -354,89 +354,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - ( - DataMigrationServiceClient, - transports.DataMigrationServiceGrpcTransport, - "grpc", - ), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-edgecontainer/CHANGELOG.md b/packages/google-cloud-edgecontainer/CHANGELOG.md index f1f5a638ff61..b96b4016f69e 100644 --- a/packages/google-cloud-edgecontainer/CHANGELOG.md +++ b/packages/google-cloud-edgecontainer/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## [0.5.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-edgecontainer-v0.5.12...google-cloud-edgecontainer-v0.5.13) (2024-10-31) + + +### Features + +* add config data to zone metadata ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) +* add connection state to cluster ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) +* add maintenance exclusion window to maintenance policy ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) +* add resource state to control plane encryption ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) +* add resource state to local disk encryption ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) +* add status reason to operation metadata ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) +* add storage schema to local control plane config ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) +* add storage schema to node config ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) +* add VM service config to system addons config ([a0f0c7e](https://github.com/googleapis/google-cloud-python/commit/a0f0c7ee4045081927f9c3241cfff8e0c916798f)) + ## [0.5.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-edgecontainer-v0.5.11...google-cloud-edgecontainer-v0.5.12) (2024-10-24) diff --git a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer/__init__.py b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer/__init__.py index b5ce893dd266..7edaa4a92f75 100644 --- a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer/__init__.py +++ b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer/__init__.py @@ -30,15 +30,18 @@ Cluster, ClusterNetworking, ClusterUser, + ConfigData, Fleet, KmsKeyState, LocationMetadata, Machine, + MaintenanceExclusionWindow, MaintenancePolicy, MaintenanceWindow, NodePool, Quota, RecurringTimeWindow, + ResourceState, ServerConfig, TimeWindow, Version, @@ -83,9 +86,11 @@ "Cluster", "ClusterNetworking", "ClusterUser", + "ConfigData", "Fleet", "LocationMetadata", "Machine", + "MaintenanceExclusionWindow", "MaintenancePolicy", "MaintenanceWindow", "NodePool", @@ -97,6 +102,7 @@ "VpnConnection", "ZoneMetadata", "KmsKeyState", + "ResourceState", "CreateClusterRequest", "CreateNodePoolRequest", "CreateVpnConnectionRequest", diff --git a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer/gapic_version.py b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer/gapic_version.py index cc43a639a105..bf678492aaad 100644 --- a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer/gapic_version.py +++ b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.12" # {x-release-please-version} +__version__ = "0.5.13" # {x-release-please-version} diff --git a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/__init__.py b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/__init__.py index 49fec7b68396..5b55c49956f0 100644 --- a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/__init__.py +++ b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/__init__.py @@ -25,15 +25,18 @@ Cluster, ClusterNetworking, ClusterUser, + ConfigData, Fleet, KmsKeyState, LocationMetadata, Machine, + MaintenanceExclusionWindow, MaintenancePolicy, MaintenanceWindow, NodePool, Quota, RecurringTimeWindow, + ResourceState, ServerConfig, TimeWindow, Version, @@ -77,6 +80,7 @@ "Cluster", "ClusterNetworking", "ClusterUser", + "ConfigData", "CreateClusterRequest", "CreateNodePoolRequest", "CreateVpnConnectionRequest", @@ -105,12 +109,14 @@ "ListVpnConnectionsResponse", "LocationMetadata", "Machine", + "MaintenanceExclusionWindow", "MaintenancePolicy", "MaintenanceWindow", "NodePool", "OperationMetadata", "Quota", "RecurringTimeWindow", + "ResourceState", "ServerConfig", "TimeWindow", "UpdateClusterRequest", diff --git a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/gapic_version.py b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/gapic_version.py index cc43a639a105..bf678492aaad 100644 --- a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/gapic_version.py +++ b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.12" # {x-release-please-version} +__version__ = "0.5.13" # {x-release-please-version} diff --git a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/__init__.py b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/__init__.py index b50f7e493939..551f3fae0201 100644 --- a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/__init__.py +++ b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/__init__.py @@ -19,15 +19,18 @@ Cluster, ClusterNetworking, ClusterUser, + ConfigData, Fleet, KmsKeyState, LocationMetadata, Machine, + MaintenanceExclusionWindow, MaintenancePolicy, MaintenanceWindow, NodePool, Quota, RecurringTimeWindow, + ResourceState, ServerConfig, TimeWindow, Version, @@ -70,9 +73,11 @@ "Cluster", "ClusterNetworking", "ClusterUser", + "ConfigData", "Fleet", "LocationMetadata", "Machine", + "MaintenanceExclusionWindow", "MaintenancePolicy", "MaintenanceWindow", "NodePool", @@ -84,6 +89,7 @@ "VpnConnection", "ZoneMetadata", "KmsKeyState", + "ResourceState", "CreateClusterRequest", "CreateNodePoolRequest", "CreateVpnConnectionRequest", diff --git a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/resources.py b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/resources.py index e64ea67ca0d5..c856d97aa1c4 100644 --- a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/resources.py +++ b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/resources.py @@ -26,6 +26,7 @@ package="google.cloud.edgecontainer.v1", manifest={ "KmsKeyState", + "ResourceState", "Cluster", "ClusterNetworking", "Fleet", @@ -36,10 +37,12 @@ "VpnConnection", "LocationMetadata", "ZoneMetadata", + "ConfigData", "Quota", "MaintenancePolicy", "MaintenanceWindow", "RecurringTimeWindow", + "MaintenanceExclusionWindow", "TimeWindow", "ServerConfig", "ChannelConfig", @@ -67,6 +70,22 @@ class KmsKeyState(proto.Enum): KMS_KEY_STATE_KEY_UNAVAILABLE = 2 +class ResourceState(proto.Enum): + r"""Represents if the resource is in lock down state or pending. + + Values: + RESOURCE_STATE_UNSPECIFIED (0): + Default value. + RESOURCE_STATE_LOCK_DOWN (1): + The resource is in LOCK DOWN state. + RESOURCE_STATE_LOCK_DOWN_PENDING (2): + The resource is pending lock down. + """ + RESOURCE_STATE_UNSPECIFIED = 0 + RESOURCE_STATE_LOCK_DOWN = 1 + RESOURCE_STATE_LOCK_DOWN_PENDING = 2 + + class Cluster(proto.Message): r"""A Google Distributed Cloud Edge Kubernetes cluster. @@ -149,6 +168,9 @@ class Cluster(proto.Message): external_load_balancer_ipv6_address_pools (MutableSequence[str]): Optional. IPv6 address pools for cluster data plane external load balancing. + connection_state (google.cloud.edgecontainer_v1.types.Cluster.ConnectionState): + Output only. The current connection state of + the cluster. """ class Status(proto.Enum): @@ -274,6 +296,13 @@ class Local(proto.Message): shared_deployment_policy (google.cloud.edgecontainer_v1.types.Cluster.ControlPlane.SharedDeploymentPolicy): Policy configuration about how user applications are deployed. + control_plane_node_storage_schema (str): + Optional. Name for the storage schema of + control plane nodes. + Warning: Configurable node local storage schema + feature is an experimental feature, and is not + recommended for general use in production + clusters/nodepools. """ node_location: str = proto.Field( @@ -295,6 +324,10 @@ class Local(proto.Message): enum="Cluster.ControlPlane.SharedDeploymentPolicy", ) ) + control_plane_node_storage_schema: str = proto.Field( + proto.STRING, + number=5, + ) remote: "Cluster.ControlPlane.Remote" = proto.Field( proto.MESSAGE, @@ -316,6 +349,8 @@ class SystemAddonsConfig(proto.Message): Attributes: ingress (google.cloud.edgecontainer_v1.types.Cluster.SystemAddonsConfig.Ingress): Optional. Config for Ingress. + vm_service_config (google.cloud.edgecontainer_v1.types.Cluster.SystemAddonsConfig.VMServiceConfig): + Optional. Config for VM Service. """ class Ingress(proto.Message): @@ -340,19 +375,38 @@ class Ingress(proto.Message): number=2, ) + class VMServiceConfig(proto.Message): + r"""VMServiceConfig defines the configuration for GDCE VM + Service. + + Attributes: + vmm_enabled (bool): + Optional. Whether VMM is enabled. + """ + + vmm_enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + ingress: "Cluster.SystemAddonsConfig.Ingress" = proto.Field( proto.MESSAGE, number=1, message="Cluster.SystemAddonsConfig.Ingress", ) + vm_service_config: "Cluster.SystemAddonsConfig.VMServiceConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="Cluster.SystemAddonsConfig.VMServiceConfig", + ) class ControlPlaneEncryption(proto.Message): - r"""Configuration for Customer-managed KMS key support for remote - control plane cluster disk encryption. + r"""Configuration for Customer-managed KMS key support for + control plane nodes. Attributes: kms_key (str): - Immutable. The Cloud KMS CryptoKey e.g. + Optional. The Cloud KMS CryptoKey e.g. projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey} to use for protecting control plane disks. If not specified, a Google-managed key will be used @@ -373,6 +427,9 @@ class ControlPlaneEncryption(proto.Message): ``kms_key_state`` is not ``KMS_KEY_STATE_KEY_AVAILABLE``. If populated, this field contains the error status reported by Cloud KMS. + resource_state (google.cloud.edgecontainer_v1.types.ResourceState): + Output only. The current resource state + associated with the cmek. """ kms_key: str = proto.Field( @@ -393,6 +450,11 @@ class ControlPlaneEncryption(proto.Message): number=4, message=status_pb2.Status, ) + resource_state: "ResourceState" = proto.Field( + proto.ENUM, + number=5, + enum="ResourceState", + ) class MaintenanceEvent(proto.Message): r"""A Maintenance Event is an operation that could cause @@ -551,6 +613,51 @@ class SurvivabilityConfig(proto.Message): message=duration_pb2.Duration, ) + class ConnectionState(proto.Message): + r"""ConnectionState holds the current connection state from the + cluster to Google. + + Attributes: + state (google.cloud.edgecontainer_v1.types.Cluster.ConnectionState.State): + Output only. The current connection state. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the connection + state was last changed. + """ + + class State(proto.Enum): + r"""The connection state. + + Values: + STATE_UNSPECIFIED (0): + Unknown connection state. + DISCONNECTED (1): + This cluster is currently disconnected from + Google. + CONNECTED (2): + This cluster is currently connected to + Google. + CONNECTED_AND_SYNCING (3): + This cluster is currently connected to + Google, but may have recently reconnected after + a disconnection. It is still syncing back. + """ + STATE_UNSPECIFIED = 0 + DISCONNECTED = 1 + CONNECTED = 2 + CONNECTED_AND_SYNCING = 3 + + state: "Cluster.ConnectionState.State" = proto.Field( + proto.ENUM, + number=1, + enum="Cluster.ConnectionState.State", + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -665,6 +772,11 @@ class SurvivabilityConfig(proto.Message): proto.STRING, number=25, ) + connection_state: ConnectionState = proto.Field( + proto.MESSAGE, + number=27, + message=ConnectionState, + ) class ClusterNetworking(proto.Message): @@ -801,7 +913,7 @@ class LocalDiskEncryption(proto.Message): Attributes: kms_key (str): - Immutable. The Cloud KMS CryptoKey e.g. + Optional. The Cloud KMS CryptoKey e.g. projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey} to use for protecting node local disks. If not specified, a Google-managed key will be used @@ -822,6 +934,9 @@ class LocalDiskEncryption(proto.Message): ``kms_key_state`` is not ``KMS_KEY_STATE_KEY_AVAILABLE``. If populated, this field contains the error status reported by Cloud KMS. + resource_state (google.cloud.edgecontainer_v1.types.ResourceState): + Output only. The current resource state + associated with the cmek. """ kms_key: str = proto.Field( @@ -842,6 +957,11 @@ class LocalDiskEncryption(proto.Message): number=4, message=status_pb2.Status, ) + resource_state: "ResourceState" = proto.Field( + proto.ENUM, + number=5, + enum="ResourceState", + ) class NodeConfig(proto.Message): r"""Configuration for each node in the NodePool @@ -849,6 +969,13 @@ class NodeConfig(proto.Message): Attributes: labels (MutableMapping[str, str]): Optional. The Kubernetes node labels + node_storage_schema (str): + Optional. Name for the storage schema of + worker nodes. + Warning: Configurable node local storage schema + feature is an experimental feature, and is not + recommended for general use in production + clusters/nodepools. """ labels: MutableMapping[str, str] = proto.MapField( @@ -856,6 +983,10 @@ class NodeConfig(proto.Message): proto.STRING, number=1, ) + node_storage_schema: str = proto.Field( + proto.STRING, + number=2, + ) name: str = proto.Field( proto.STRING, @@ -1047,13 +1178,7 @@ class VpcProject(proto.Message): specified, it is the same as the cluster project. service_account (str): - Optional. The service account in the VPC project configured - by user. It is used to create/delete Cloud Router and Cloud - HA VPNs for VPN connection. If this SA is changed - during/after a VPN connection is created, you need to remove - the Cloud Router and Cloud VPN resources in \|project_id|. - It is in the form of - service-{project_number}@gcp-sa-edgecontainer.iam.gserviceaccount.com. + Optional. Deprecated: do not use. """ project_id: str = proto.Field( @@ -1232,6 +1357,8 @@ class ZoneMetadata(proto.Message): rack_types (MutableMapping[str, google.cloud.edgecontainer_v1.types.ZoneMetadata.RackType]): The map keyed by rack name and has value of RackType. + config_data (google.cloud.edgecontainer_v1.types.ConfigData): + Config data for the zone. """ class RackType(proto.Enum): @@ -1263,6 +1390,33 @@ class RackType(proto.Enum): number=2, enum=RackType, ) + config_data: "ConfigData" = proto.Field( + proto.MESSAGE, + number=3, + message="ConfigData", + ) + + +class ConfigData(proto.Message): + r"""Config data holds all the config related data for the zone. + + Attributes: + available_external_lb_pools_ipv4 (MutableSequence[str]): + list of available v4 ip pools for external + loadbalancer + available_external_lb_pools_ipv6 (MutableSequence[str]): + list of available v6 ip pools for external + loadbalancer + """ + + available_external_lb_pools_ipv4: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + available_external_lb_pools_ipv6: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) class Quota(proto.Message): @@ -1298,6 +1452,13 @@ class MaintenancePolicy(proto.Message): window (google.cloud.edgecontainer_v1.types.MaintenanceWindow): Specifies the maintenance window in which maintenance may be performed. + maintenance_exclusions (MutableSequence[google.cloud.edgecontainer_v1.types.MaintenanceExclusionWindow]): + Optional. Exclusions to automatic + maintenance. Non-emergency maintenance should + not occur in these windows. Each exclusion has a + unique name and may be active or expired. The + max number of maintenance exclusions allowed at + a given time is 3. """ window: "MaintenanceWindow" = proto.Field( @@ -1305,6 +1466,13 @@ class MaintenancePolicy(proto.Message): number=1, message="MaintenanceWindow", ) + maintenance_exclusions: MutableSequence[ + "MaintenanceExclusionWindow" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="MaintenanceExclusionWindow", + ) class MaintenanceWindow(proto.Message): @@ -1347,6 +1515,28 @@ class RecurringTimeWindow(proto.Message): ) +class MaintenanceExclusionWindow(proto.Message): + r"""Represents a maintenance exclusion window. + + Attributes: + window (google.cloud.edgecontainer_v1.types.TimeWindow): + Optional. The time window. + id (str): + Optional. A unique (per cluster) id for the + window. + """ + + window: "TimeWindow" = proto.Field( + proto.MESSAGE, + number=1, + message="TimeWindow", + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + + class TimeWindow(proto.Message): r"""Represents an arbitrary window of time. diff --git a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/service.py b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/service.py index caf6db7abe1a..266db3e7ae28 100644 --- a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/service.py +++ b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/types/service.py @@ -86,8 +86,23 @@ class OperationMetadata(proto.Message): Warnings that do not block the operation, but still hold relevant information for the end user to receive. + status_reason (google.cloud.edgecontainer_v1.types.OperationMetadata.StatusReason): + Machine-readable status of the operation, if + any. """ + class StatusReason(proto.Enum): + r"""Indicates the reason for the status of the operation. + + Values: + STATUS_REASON_UNSPECIFIED (0): + Reason unknown. + UPGRADE_PAUSED (1): + The cluster upgrade is currently paused. + """ + STATUS_REASON_UNSPECIFIED = 0 + UPGRADE_PAUSED = 1 + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=1, @@ -122,6 +137,11 @@ class OperationMetadata(proto.Message): proto.STRING, number=8, ) + status_reason: StatusReason = proto.Field( + proto.ENUM, + number=9, + enum=StatusReason, + ) class ListClustersRequest(proto.Message): diff --git a/packages/google-cloud-edgecontainer/samples/generated_samples/snippet_metadata_google.cloud.edgecontainer.v1.json b/packages/google-cloud-edgecontainer/samples/generated_samples/snippet_metadata_google.cloud.edgecontainer.v1.json index e6339b84e6a8..6e266f3b9fca 100644 --- a/packages/google-cloud-edgecontainer/samples/generated_samples/snippet_metadata_google.cloud.edgecontainer.v1.json +++ b/packages/google-cloud-edgecontainer/samples/generated_samples/snippet_metadata_google.cloud.edgecontainer.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-edgecontainer", - "version": "0.5.12" + "version": "0.5.13" }, "snippets": [ { diff --git a/packages/google-cloud-edgecontainer/tests/unit/gapic/edgecontainer_v1/test_edge_container.py b/packages/google-cloud-edgecontainer/tests/unit/gapic/edgecontainer_v1/test_edge_container.py index b28e8b5d531a..368cc92e1b99 100644 --- a/packages/google-cloud-edgecontainer/tests/unit/gapic/edgecontainer_v1/test_edge_container.py +++ b/packages/google-cloud-edgecontainer/tests/unit/gapic/edgecontainer_v1/test_edge_container.py @@ -14157,7 +14157,8 @@ def test_create_cluster_rest_call_success(request_type): "window": {"start_time": {}, "end_time": {}}, "recurrence": "recurrence_value", } - } + }, + "maintenance_exclusions": [{"window": {}, "id": "id_value"}], }, "control_plane_version": "control_plane_version_value", "node_version": "node_version_value", @@ -14168,10 +14169,12 @@ def test_create_cluster_rest_call_success(request_type): "node_count": 1070, "machine_filter": "machine_filter_value", "shared_deployment_policy": 1, + "control_plane_node_storage_schema": "control_plane_node_storage_schema_value", }, }, "system_addons_config": { - "ingress": {"disabled": True, "ipv4_vip": "ipv4_vip_value"} + "ingress": {"disabled": True, "ipv4_vip": "ipv4_vip_value"}, + "vm_service_config": {"vmm_enabled": True}, }, "external_load_balancer_ipv4_address_pools": [ "external_load_balancer_ipv4_address_pools_value1", @@ -14191,6 +14194,7 @@ def test_create_cluster_rest_call_success(request_type): } ], }, + "resource_state": 1, }, "status": 1, "maintenance_events": [ @@ -14214,6 +14218,7 @@ def test_create_cluster_rest_call_success(request_type): "external_load_balancer_ipv6_address_pools_value1", "external_load_balancer_ipv6_address_pools_value2", ], + "connection_state": {"state": 1, "update_time": {}}, } # 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 @@ -14424,7 +14429,8 @@ def test_update_cluster_rest_call_success(request_type): "window": {"start_time": {}, "end_time": {}}, "recurrence": "recurrence_value", } - } + }, + "maintenance_exclusions": [{"window": {}, "id": "id_value"}], }, "control_plane_version": "control_plane_version_value", "node_version": "node_version_value", @@ -14435,10 +14441,12 @@ def test_update_cluster_rest_call_success(request_type): "node_count": 1070, "machine_filter": "machine_filter_value", "shared_deployment_policy": 1, + "control_plane_node_storage_schema": "control_plane_node_storage_schema_value", }, }, "system_addons_config": { - "ingress": {"disabled": True, "ipv4_vip": "ipv4_vip_value"} + "ingress": {"disabled": True, "ipv4_vip": "ipv4_vip_value"}, + "vm_service_config": {"vmm_enabled": True}, }, "external_load_balancer_ipv4_address_pools": [ "external_load_balancer_ipv4_address_pools_value1", @@ -14458,6 +14466,7 @@ def test_update_cluster_rest_call_success(request_type): } ], }, + "resource_state": 1, }, "status": 1, "maintenance_events": [ @@ -14481,6 +14490,7 @@ def test_update_cluster_rest_call_success(request_type): "external_load_balancer_ipv6_address_pools_value1", "external_load_balancer_ipv6_address_pools_value2", ], + "connection_state": {"state": 1, "update_time": {}}, } # 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 @@ -15396,9 +15406,13 @@ def test_create_node_pool_rest_call_success(request_type): } ], }, + "resource_state": 1, }, "node_version": "node_version_value", - "node_config": {"labels": {}}, + "node_config": { + "labels": {}, + "node_storage_schema": "node_storage_schema_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 @@ -15608,9 +15622,13 @@ def test_update_node_pool_rest_call_success(request_type): } ], }, + "resource_state": 1, }, "node_version": "node_version_value", - "node_config": {"labels": {}}, + "node_config": { + "labels": {}, + "node_storage_schema": "node_storage_schema_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-eventarc-publishing/CHANGELOG.md b/packages/google-cloud-eventarc-publishing/CHANGELOG.md index 3b045cb67df1..30e568597238 100644 --- a/packages/google-cloud-eventarc-publishing/CHANGELOG.md +++ b/packages/google-cloud-eventarc-publishing/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## [0.6.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-eventarc-publishing-v0.6.12...google-cloud-eventarc-publishing-v0.6.13) (2024-10-31) + + +### Features + +* Publish Eventarc Advanced Publishing API proto, allowing ([b5718b7](https://github.com/googleapis/google-cloud-python/commit/b5718b7e1196cc19e9c6e848bae19d716eb2b070)) +* Publish Eventarc Advanced Publishing API proto, allowing publishing events to a Message Bus ([#13232](https://github.com/googleapis/google-cloud-python/issues/13232)) ([b5718b7](https://github.com/googleapis/google-cloud-python/commit/b5718b7e1196cc19e9c6e848bae19d716eb2b070)) + ## [0.6.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-eventarc-publishing-v0.6.11...google-cloud-eventarc-publishing-v0.6.12) (2024-10-24) diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing/__init__.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing/__init__.py index f2f7638ddb56..94afff5dd350 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing/__init__.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing/__init__.py @@ -24,18 +24,24 @@ from google.cloud.eventarc_publishing_v1.services.publisher.client import ( PublisherClient, ) +from google.cloud.eventarc_publishing_v1.types.cloud_event import CloudEvent from google.cloud.eventarc_publishing_v1.types.publisher import ( PublishChannelConnectionEventsRequest, PublishChannelConnectionEventsResponse, PublishEventsRequest, PublishEventsResponse, + PublishRequest, + PublishResponse, ) __all__ = ( "PublisherClient", "PublisherAsyncClient", + "CloudEvent", "PublishChannelConnectionEventsRequest", "PublishChannelConnectionEventsResponse", "PublishEventsRequest", "PublishEventsResponse", + "PublishRequest", + "PublishResponse", ) diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing/gapic_version.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing/gapic_version.py index 44e5c049e336..b72badcc1eca 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing/gapic_version.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.12" # {x-release-please-version} +__version__ = "0.6.13" # {x-release-please-version} diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/__init__.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/__init__.py index e95da6102253..a4a11a63a1a3 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/__init__.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/__init__.py @@ -19,18 +19,24 @@ from .services.publisher import PublisherAsyncClient, PublisherClient +from .types.cloud_event import CloudEvent from .types.publisher import ( PublishChannelConnectionEventsRequest, PublishChannelConnectionEventsResponse, PublishEventsRequest, PublishEventsResponse, + PublishRequest, + PublishResponse, ) __all__ = ( "PublisherAsyncClient", + "CloudEvent", "PublishChannelConnectionEventsRequest", "PublishChannelConnectionEventsResponse", "PublishEventsRequest", "PublishEventsResponse", + "PublishRequest", + "PublishResponse", "PublisherClient", ) diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/gapic_metadata.json b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/gapic_metadata.json index e3ed38d1e4ce..4e12fec4741e 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/gapic_metadata.json +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/gapic_metadata.json @@ -10,6 +10,11 @@ "grpc": { "libraryClient": "PublisherClient", "rpcs": { + "Publish": { + "methods": [ + "publish" + ] + }, "PublishChannelConnectionEvents": { "methods": [ "publish_channel_connection_events" @@ -25,6 +30,11 @@ "grpc-async": { "libraryClient": "PublisherAsyncClient", "rpcs": { + "Publish": { + "methods": [ + "publish" + ] + }, "PublishChannelConnectionEvents": { "methods": [ "publish_channel_connection_events" @@ -40,6 +50,11 @@ "rest": { "libraryClient": "PublisherClient", "rpcs": { + "Publish": { + "methods": [ + "publish" + ] + }, "PublishChannelConnectionEvents": { "methods": [ "publish_channel_connection_events" diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/gapic_version.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/gapic_version.py index 44e5c049e336..b72badcc1eca 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/gapic_version.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.12" # {x-release-please-version} +__version__ = "0.6.13" # {x-release-please-version} diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/async_client.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/async_client.py index 2039a452d57f..3fd2a5eb6144 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/async_client.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/async_client.py @@ -444,6 +444,98 @@ async def sample_publish_events(): # Done; return the response. return response + async def publish( + self, + request: Optional[Union[publisher.PublishRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> publisher.PublishResponse: + r"""Publish events to a message bus. + + .. 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 eventarc_publishing_v1 + + async def sample_publish(): + # Create a client + client = eventarc_publishing_v1.PublisherAsyncClient() + + # Initialize request argument(s) + proto_message = eventarc_publishing_v1.CloudEvent() + proto_message.binary_data = b'binary_data_blob' + proto_message.id = "id_value" + proto_message.source = "source_value" + proto_message.spec_version = "spec_version_value" + proto_message.type_ = "type__value" + + request = eventarc_publishing_v1.PublishRequest( + proto_message=proto_message, + message_bus="message_bus_value", + ) + + # Make the request + response = await client.publish(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_publishing_v1.types.PublishRequest, dict]]): + The request object. The request message for the Publish + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_publishing_v1.types.PublishResponse: + The response message for the Publish + method. + + """ + # 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, publisher.PublishRequest): + request = publisher.PublishRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.publish] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("message_bus", request.message_bus),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "PublisherAsyncClient": return self diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/client.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/client.py index ab5ecc27a959..6c284c2661c4 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/client.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/client.py @@ -846,6 +846,98 @@ def sample_publish_events(): # Done; return the response. return response + def publish( + self, + request: Optional[Union[publisher.PublishRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> publisher.PublishResponse: + r"""Publish events to a message bus. + + .. 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 eventarc_publishing_v1 + + def sample_publish(): + # Create a client + client = eventarc_publishing_v1.PublisherClient() + + # Initialize request argument(s) + proto_message = eventarc_publishing_v1.CloudEvent() + proto_message.binary_data = b'binary_data_blob' + proto_message.id = "id_value" + proto_message.source = "source_value" + proto_message.spec_version = "spec_version_value" + proto_message.type_ = "type__value" + + request = eventarc_publishing_v1.PublishRequest( + proto_message=proto_message, + message_bus="message_bus_value", + ) + + # Make the request + response = client.publish(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_publishing_v1.types.PublishRequest, dict]): + The request object. The request message for the Publish + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_publishing_v1.types.PublishResponse: + The response message for the Publish + method. + + """ + # 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, publisher.PublishRequest): + request = publisher.PublishRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.publish] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("message_bus", request.message_bus),) + ), + ) + + # 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) -> "PublisherClient": return self diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/base.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/base.py index 3a14c4a53df4..80b3dc29341e 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/base.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/base.py @@ -138,6 +138,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.publish: gapic_v1.method.wrap_method( + self.publish, + default_timeout=60.0, + client_info=client_info, + ), } def close(self): @@ -172,6 +177,15 @@ def publish_events( ]: raise NotImplementedError() + @property + def publish( + self, + ) -> Callable[ + [publisher.PublishRequest], + Union[publisher.PublishResponse, Awaitable[publisher.PublishResponse]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/grpc.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/grpc.py index b2e4e039c024..a18c96cc1893 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/grpc.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/grpc.py @@ -320,6 +320,32 @@ def publish_events( ) return self._stubs["publish_events"] + @property + def publish( + self, + ) -> Callable[[publisher.PublishRequest], publisher.PublishResponse]: + r"""Return a callable for the publish method over gRPC. + + Publish events to a message bus. + + Returns: + Callable[[~.PublishRequest], + ~.PublishResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "publish" not in self._stubs: + self._stubs["publish"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.publishing.v1.Publisher/Publish", + request_serializer=publisher.PublishRequest.serialize, + response_deserializer=publisher.PublishResponse.deserialize, + ) + return self._stubs["publish"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/grpc_asyncio.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/grpc_asyncio.py index ffb9f5fa7e80..8a15731de02f 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/grpc_asyncio.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/grpc_asyncio.py @@ -330,6 +330,32 @@ def publish_events( ) return self._stubs["publish_events"] + @property + def publish( + self, + ) -> Callable[[publisher.PublishRequest], Awaitable[publisher.PublishResponse]]: + r"""Return a callable for the publish method over gRPC. + + Publish events to a message bus. + + Returns: + Callable[[~.PublishRequest], + Awaitable[~.PublishResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "publish" not in self._stubs: + self._stubs["publish"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.publishing.v1.Publisher/Publish", + request_serializer=publisher.PublishRequest.serialize, + response_deserializer=publisher.PublishResponse.deserialize, + ) + return self._stubs["publish"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -343,6 +369,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.publish: self._wrap_method( + self.publish, + default_timeout=60.0, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest.py index 69c528a8de45..33abd483c746 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest.py @@ -60,6 +60,14 @@ class PublisherRestInterceptor: .. code-block:: python class MyCustomPublisherInterceptor(PublisherRestInterceptor): + def pre_publish(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_publish(self, response): + logging.log(f"Received response: {response}") + return response + def pre_publish_channel_connection_events(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -82,6 +90,27 @@ def post_publish_events(self, response): """ + def pre_publish( + self, request: publisher.PublishRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[publisher.PublishRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for publish + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_publish( + self, response: publisher.PublishResponse + ) -> publisher.PublishResponse: + """Post-rpc interceptor for publish + + Override in a subclass to manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. + """ + return response + def pre_publish_channel_connection_events( self, request: publisher.PublishChannelConnectionEventsRequest, @@ -244,6 +273,103 @@ def __init__( self._interceptor = interceptor or PublisherRestInterceptor() self._prep_wrapped_messages(client_info) + class _Publish(_BasePublisherRestTransport._BasePublish, PublisherRestStub): + def __hash__(self): + return hash("PublisherRestTransport.Publish") + + @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: publisher.PublishRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> publisher.PublishResponse: + r"""Call the publish method over HTTP. + + Args: + request (~.publisher.PublishRequest): + The request object. The request message for the Publish + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.publisher.PublishResponse: + The response message for the Publish + method. + + """ + + http_options = _BasePublisherRestTransport._BasePublish._get_http_options() + request, metadata = self._interceptor.pre_publish(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BasePublish._get_transcoded_request( + http_options, request + ) + ) + + body = _BasePublisherRestTransport._BasePublish._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BasePublish._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = PublisherRestTransport._Publish._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 = publisher.PublishResponse() + pb_resp = publisher.PublishResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_publish(resp) + return resp + class _PublishChannelConnectionEvents( _BasePublisherRestTransport._BasePublishChannelConnectionEvents, PublisherRestStub, @@ -450,6 +576,14 @@ def __call__( resp = self._interceptor.post_publish_events(resp) return resp + @property + def publish( + self, + ) -> Callable[[publisher.PublishRequest], publisher.PublishResponse]: + # 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._Publish(self._session, self._host, self._interceptor) # type: ignore + @property def publish_channel_connection_events( self, diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest_base.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest_base.py index 11e7b69f9264..8c8808040aeb 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest_base.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/services/publisher/transports/rest_base.py @@ -87,6 +87,63 @@ def __init__( api_audience=api_audience, ) + class _BasePublish: + 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": "/v1/{message_bus=projects/*/locations/*/messageBuses/*}:publish", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = publisher.PublishRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BasePublish._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BasePublishChannelConnectionEvents: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/__init__.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/__init__.py index c7cf89dbfa7b..3648458cfc2a 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/__init__.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/__init__.py @@ -13,16 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .cloud_event import CloudEvent from .publisher import ( PublishChannelConnectionEventsRequest, PublishChannelConnectionEventsResponse, PublishEventsRequest, PublishEventsResponse, + PublishRequest, + PublishResponse, ) __all__ = ( + "CloudEvent", "PublishChannelConnectionEventsRequest", "PublishChannelConnectionEventsResponse", "PublishEventsRequest", "PublishEventsResponse", + "PublishRequest", + "PublishResponse", ) diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/cloud_event.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/cloud_event.py new file mode 100644 index 000000000000..fb60d2302f16 --- /dev/null +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/cloud_event.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.eventarc.publishing.v1", + manifest={ + "CloudEvent", + }, +) + + +class CloudEvent(proto.Message): + r"""CloudEvent represents a vendor-neutral specification for + defining the format of event data. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + Required. Identifies the event. Producers + MUST ensure that source + id is unique for each + distinct event. + source (str): + Required. Identifies the context in which an + event happened. URI-reference + spec_version (str): + Required. The version of the CloudEvents + specification which the event uses. + type_ (str): + Required. This attribute contains a value + describing the type of event related to the + originating occurrence. + attributes (MutableMapping[str, google.cloud.eventarc_publishing_v1.types.CloudEvent.CloudEventAttributeValue]): + Optional. Used for Optional & Extension + Attributes + binary_data (bytes): + Optional. Binary data. + + This field is a member of `oneof`_ ``data``. + text_data (str): + Optional. Text data. + + This field is a member of `oneof`_ ``data``. + proto_data (google.protobuf.any_pb2.Any): + Optional. Proto data. + + This field is a member of `oneof`_ ``data``. + """ + + class CloudEventAttributeValue(proto.Message): + r"""The following abstract data types are available for use in + attributes. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ce_boolean (bool): + Boolean value. + + This field is a member of `oneof`_ ``attr``. + ce_integer (int): + Integer value. + + This field is a member of `oneof`_ ``attr``. + ce_string (str): + String value. + + This field is a member of `oneof`_ ``attr``. + ce_bytes (bytes): + Bytes value. + + This field is a member of `oneof`_ ``attr``. + ce_uri (str): + URI value. + + This field is a member of `oneof`_ ``attr``. + ce_uri_ref (str): + URI-reference value. + + This field is a member of `oneof`_ ``attr``. + ce_timestamp (google.protobuf.timestamp_pb2.Timestamp): + Timestamp value. + + This field is a member of `oneof`_ ``attr``. + """ + + ce_boolean: bool = proto.Field( + proto.BOOL, + number=1, + oneof="attr", + ) + ce_integer: int = proto.Field( + proto.INT32, + number=2, + oneof="attr", + ) + ce_string: str = proto.Field( + proto.STRING, + number=3, + oneof="attr", + ) + ce_bytes: bytes = proto.Field( + proto.BYTES, + number=4, + oneof="attr", + ) + ce_uri: str = proto.Field( + proto.STRING, + number=5, + oneof="attr", + ) + ce_uri_ref: str = proto.Field( + proto.STRING, + number=6, + oneof="attr", + ) + ce_timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + oneof="attr", + message=timestamp_pb2.Timestamp, + ) + + id: str = proto.Field( + proto.STRING, + number=1, + ) + source: str = proto.Field( + proto.STRING, + number=2, + ) + spec_version: str = proto.Field( + proto.STRING, + number=3, + ) + type_: str = proto.Field( + proto.STRING, + number=4, + ) + attributes: MutableMapping[str, CloudEventAttributeValue] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=CloudEventAttributeValue, + ) + binary_data: bytes = proto.Field( + proto.BYTES, + number=6, + oneof="data", + ) + text_data: str = proto.Field( + proto.STRING, + number=7, + oneof="data", + ) + proto_data: any_pb2.Any = proto.Field( + proto.MESSAGE, + number=8, + oneof="data", + message=any_pb2.Any, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/publisher.py b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/publisher.py index 41505c774e32..1605dcf44b95 100644 --- a/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/publisher.py +++ b/packages/google-cloud-eventarc-publishing/google/cloud/eventarc_publishing_v1/types/publisher.py @@ -20,6 +20,8 @@ from google.protobuf import any_pb2 # type: ignore import proto # type: ignore +from google.cloud.eventarc_publishing_v1.types import cloud_event + __protobuf__ = proto.module( package="google.cloud.eventarc.publishing.v1", manifest={ @@ -27,6 +29,8 @@ "PublishChannelConnectionEventsResponse", "PublishEventsRequest", "PublishEventsResponse", + "PublishRequest", + "PublishResponse", }, ) @@ -112,4 +116,68 @@ class PublishEventsResponse(proto.Message): r"""The response message for the PublishEvents method.""" +class PublishRequest(proto.Message): + r"""The request message for the Publish method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + message_bus (str): + Required. The full name of the message bus to publish events + to. Format: + ``projects/{project}/locations/{location}/messageBuses/{messageBus}``. + proto_message (google.cloud.eventarc_publishing_v1.types.CloudEvent): + The Protobuf format of the CloudEvent being + published. Specification can be found here: + + https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/formats/protobuf-format.md + + This field is a member of `oneof`_ ``format``. + json_message (str): + The JSON format of the CloudEvent being + published. Specification can be found here: + + https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/formats/json-format.md + + This field is a member of `oneof`_ ``format``. + avro_message (bytes): + The Avro format of the CloudEvent being + published. Specification can be found here: + + https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/formats/avro-format.md + + This field is a member of `oneof`_ ``format``. + """ + + message_bus: str = proto.Field( + proto.STRING, + number=1, + ) + proto_message: cloud_event.CloudEvent = proto.Field( + proto.MESSAGE, + number=2, + oneof="format", + message=cloud_event.CloudEvent, + ) + json_message: str = proto.Field( + proto.STRING, + number=3, + oneof="format", + ) + avro_message: bytes = proto.Field( + proto.BYTES, + number=4, + oneof="format", + ) + + +class PublishResponse(proto.Message): + r"""The response message for the Publish method.""" + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc-publishing/samples/generated_samples/eventarcpublishing_v1_generated_publisher_publish_async.py b/packages/google-cloud-eventarc-publishing/samples/generated_samples/eventarcpublishing_v1_generated_publisher_publish_async.py new file mode 100644 index 000000000000..5f5ab5acf137 --- /dev/null +++ b/packages/google-cloud-eventarc-publishing/samples/generated_samples/eventarcpublishing_v1_generated_publisher_publish_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 Publish +# 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-eventarc-publishing + + +# [START eventarcpublishing_v1_generated_Publisher_Publish_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_publishing_v1 + + +async def sample_publish(): + # Create a client + client = eventarc_publishing_v1.PublisherAsyncClient() + + # Initialize request argument(s) + proto_message = eventarc_publishing_v1.CloudEvent() + proto_message.binary_data = b'binary_data_blob' + proto_message.id = "id_value" + proto_message.source = "source_value" + proto_message.spec_version = "spec_version_value" + proto_message.type_ = "type__value" + + request = eventarc_publishing_v1.PublishRequest( + proto_message=proto_message, + message_bus="message_bus_value", + ) + + # Make the request + response = await client.publish(request=request) + + # Handle the response + print(response) + +# [END eventarcpublishing_v1_generated_Publisher_Publish_async] diff --git a/packages/google-cloud-eventarc-publishing/samples/generated_samples/eventarcpublishing_v1_generated_publisher_publish_sync.py b/packages/google-cloud-eventarc-publishing/samples/generated_samples/eventarcpublishing_v1_generated_publisher_publish_sync.py new file mode 100644 index 000000000000..75a0796d05cb --- /dev/null +++ b/packages/google-cloud-eventarc-publishing/samples/generated_samples/eventarcpublishing_v1_generated_publisher_publish_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 Publish +# 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-eventarc-publishing + + +# [START eventarcpublishing_v1_generated_Publisher_Publish_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 eventarc_publishing_v1 + + +def sample_publish(): + # Create a client + client = eventarc_publishing_v1.PublisherClient() + + # Initialize request argument(s) + proto_message = eventarc_publishing_v1.CloudEvent() + proto_message.binary_data = b'binary_data_blob' + proto_message.id = "id_value" + proto_message.source = "source_value" + proto_message.spec_version = "spec_version_value" + proto_message.type_ = "type__value" + + request = eventarc_publishing_v1.PublishRequest( + proto_message=proto_message, + message_bus="message_bus_value", + ) + + # Make the request + response = client.publish(request=request) + + # Handle the response + print(response) + +# [END eventarcpublishing_v1_generated_Publisher_Publish_sync] diff --git a/packages/google-cloud-eventarc-publishing/samples/generated_samples/snippet_metadata_google.cloud.eventarc.publishing.v1.json b/packages/google-cloud-eventarc-publishing/samples/generated_samples/snippet_metadata_google.cloud.eventarc.publishing.v1.json index 03855a295d4d..b996c32a8776 100644 --- a/packages/google-cloud-eventarc-publishing/samples/generated_samples/snippet_metadata_google.cloud.eventarc.publishing.v1.json +++ b/packages/google-cloud-eventarc-publishing/samples/generated_samples/snippet_metadata_google.cloud.eventarc.publishing.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-eventarc-publishing", - "version": "0.6.12" + "version": "0.6.13" }, "snippets": [ { @@ -316,6 +316,159 @@ } ], "title": "eventarcpublishing_v1_generated_publisher_publish_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_publishing_v1.PublisherAsyncClient", + "shortName": "PublisherAsyncClient" + }, + "fullName": "google.cloud.eventarc_publishing_v1.PublisherAsyncClient.publish", + "method": { + "fullName": "google.cloud.eventarc.publishing.v1.Publisher.Publish", + "service": { + "fullName": "google.cloud.eventarc.publishing.v1.Publisher", + "shortName": "Publisher" + }, + "shortName": "Publish" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_publishing_v1.types.PublishRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_publishing_v1.types.PublishResponse", + "shortName": "publish" + }, + "description": "Sample for Publish", + "file": "eventarcpublishing_v1_generated_publisher_publish_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarcpublishing_v1_generated_Publisher_Publish_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarcpublishing_v1_generated_publisher_publish_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_publishing_v1.PublisherClient", + "shortName": "PublisherClient" + }, + "fullName": "google.cloud.eventarc_publishing_v1.PublisherClient.publish", + "method": { + "fullName": "google.cloud.eventarc.publishing.v1.Publisher.Publish", + "service": { + "fullName": "google.cloud.eventarc.publishing.v1.Publisher", + "shortName": "Publisher" + }, + "shortName": "Publish" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_publishing_v1.types.PublishRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_publishing_v1.types.PublishResponse", + "shortName": "publish" + }, + "description": "Sample for Publish", + "file": "eventarcpublishing_v1_generated_publisher_publish_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarcpublishing_v1_generated_Publisher_Publish_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarcpublishing_v1_generated_publisher_publish_sync.py" } ] } diff --git a/packages/google-cloud-eventarc-publishing/scripts/fixup_eventarc_publishing_v1_keywords.py b/packages/google-cloud-eventarc-publishing/scripts/fixup_eventarc_publishing_v1_keywords.py index e0c0257f84c9..fa03e6835616 100644 --- a/packages/google-cloud-eventarc-publishing/scripts/fixup_eventarc_publishing_v1_keywords.py +++ b/packages/google-cloud-eventarc-publishing/scripts/fixup_eventarc_publishing_v1_keywords.py @@ -39,6 +39,7 @@ def partition( class eventarc_publishingCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'publish': ('message_bus', 'proto_message', 'json_message', 'avro_message', ), 'publish_channel_connection_events': ('channel_connection', 'events', 'text_events', ), 'publish_events': ('channel', 'events', 'text_events', ), } diff --git a/packages/google-cloud-eventarc-publishing/tests/unit/gapic/eventarc_publishing_v1/test_publisher.py b/packages/google-cloud-eventarc-publishing/tests/unit/gapic/eventarc_publishing_v1/test_publisher.py index 2d2fa9babc9d..e79ed1388727 100644 --- a/packages/google-cloud-eventarc-publishing/tests/unit/gapic/eventarc_publishing_v1/test_publisher.py +++ b/packages/google-cloud-eventarc-publishing/tests/unit/gapic/eventarc_publishing_v1/test_publisher.py @@ -52,13 +52,14 @@ from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.eventarc_publishing_v1.services.publisher import ( PublisherAsyncClient, PublisherClient, transports, ) -from google.cloud.eventarc_publishing_v1.types import publisher +from google.cloud.eventarc_publishing_v1.types import cloud_event, publisher async def mock_async_gen(data, chunk_size=1): @@ -1581,6 +1582,241 @@ async def test_publish_events_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + publisher.PublishRequest, + dict, + ], +) +def test_publish(request_type, transport: str = "grpc"): + client = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.publish), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = publisher.PublishResponse() + response = client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = publisher.PublishRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, publisher.PublishResponse) + + +def test_publish_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = publisher.PublishRequest( + message_bus="message_bus_value", + json_message="json_message_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.publish), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.publish(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == publisher.PublishRequest( + message_bus="message_bus_value", + json_message="json_message_value", + ) + + +def test_publish_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 = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.publish 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.publish] = mock_rpc + request = {} + client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.publish(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_publish_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PublisherAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.publish + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.publish + ] = mock_rpc + + request = {} + await client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.publish(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_publish_async( + transport: str = "grpc_asyncio", request_type=publisher.PublishRequest +): + client = PublisherAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.publish), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + publisher.PublishResponse() + ) + response = await client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = publisher.PublishRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, publisher.PublishResponse) + + +@pytest.mark.asyncio +async def test_publish_async_from_dict(): + await test_publish_async(request_type=dict) + + +def test_publish_field_headers(): + client = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = publisher.PublishRequest() + + request.message_bus = "message_bus_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.publish), "__call__") as call: + call.return_value = publisher.PublishResponse() + client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "message_bus=message_bus_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_publish_field_headers_async(): + client = PublisherAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = publisher.PublishRequest() + + request.message_bus = "message_bus_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.publish), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + publisher.PublishResponse() + ) + await client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "message_bus=message_bus_value", + ) in kw["metadata"] + + def test_publish_channel_connection_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1658,6 +1894,124 @@ def test_publish_events_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 +def test_publish_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 = PublisherClient( + 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.publish 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.publish] = mock_rpc + + request = {} + client.publish(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.publish(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_publish_rest_required_fields(request_type=publisher.PublishRequest): + transport_class = transports.PublisherRestTransport + + request_init = {} + request_init["message_bus"] = "" + 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() + ).publish._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["messageBus"] = "message_bus_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).publish._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "messageBus" in jsonified_request + assert jsonified_request["messageBus"] == "message_bus_value" + + client = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = publisher.PublishResponse() + # 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 = publisher.PublishResponse.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 + + response = client.publish(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_publish_rest_unset_required_fields(): + transport = transports.PublisherRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.publish._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("messageBus",))) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PublisherGrpcTransport( @@ -1808,6 +2162,27 @@ def test_publish_events_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_publish_empty_call_grpc(): + client = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.publish), "__call__") as call: + call.return_value = publisher.PublishResponse() + client.publish(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = publisher.PublishRequest() + + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = PublisherAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -1874,6 +2249,31 @@ async def test_publish_events_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_publish_empty_call_grpc_asyncio(): + client = PublisherAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.publish), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + publisher.PublishResponse() + ) + await client.publish(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = publisher.PublishRequest() + + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = PublisherClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -2113,6 +2513,120 @@ def test_publish_events_rest_interceptors(null_interceptor): post.assert_called_once() +def test_publish_rest_bad_request(request_type=publisher.PublishRequest): + client = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "message_bus": "projects/sample1/locations/sample2/messageBuses/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 + client.publish(request) + + +@pytest.mark.parametrize( + "request_type", + [ + publisher.PublishRequest, + dict, + ], +) +def test_publish_rest_call_success(request_type): + client = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "message_bus": "projects/sample1/locations/sample2/messageBuses/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 = publisher.PublishResponse() + + # 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 = publisher.PublishResponse.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 + response = client.publish(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, publisher.PublishResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_publish_rest_interceptors(null_interceptor): + transport = transports.PublisherRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PublisherRestInterceptor(), + ) + client = PublisherClient(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.PublisherRestInterceptor, "post_publish" + ) as post, mock.patch.object( + transports.PublisherRestInterceptor, "pre_publish" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = publisher.PublishRequest.pb(publisher.PublishRequest()) + 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 + return_value = publisher.PublishResponse.to_json(publisher.PublishResponse()) + req.return_value.content = return_value + + request = publisher.PublishRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = publisher.PublishResponse() + + client.publish( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + def test_initialize_client_w_rest(): client = PublisherClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2162,6 +2676,26 @@ def test_publish_events_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_publish_empty_call_rest(): + client = PublisherClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.publish), "__call__") as call: + client.publish(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = publisher.PublishRequest() + + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = PublisherClient( @@ -2197,6 +2731,7 @@ def test_publisher_base_transport(): methods = ( "publish_channel_connection_events", "publish_events", + "publish", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2458,6 +2993,9 @@ def test_publisher_client_transport_session_collision(transport_name): session1 = client1.transport.publish_events._session session2 = client2.transport.publish_events._session assert session1 != session2 + session1 = client1.transport.publish._session + session2 = client2.transport.publish._session + assert session1 != session2 def test_publisher_grpc_transport_channel(): diff --git a/packages/google-cloud-eventarc/CHANGELOG.md b/packages/google-cloud-eventarc/CHANGELOG.md index 54a99696ebb7..560c1a8c30c6 100644 --- a/packages/google-cloud-eventarc/CHANGELOG.md +++ b/packages/google-cloud-eventarc/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## [1.13.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-eventarc-v1.12.0...google-cloud-eventarc-v1.13.0) (2024-10-31) + + +### Features + +* Publish Eventarc Advanced protos ([e90120b](https://github.com/googleapis/google-cloud-python/commit/e90120b0661c17acfdeec5f3edb37c4155c19aa6)) + + +### Documentation + +* Clarified multiple comments in Eventarc Standard protos ([e90120b](https://github.com/googleapis/google-cloud-python/commit/e90120b0661c17acfdeec5f3edb37c4155c19aa6)) + ## [1.12.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-eventarc-v1.11.5...google-cloud-eventarc-v1.12.0) (2024-10-24) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc/__init__.py b/packages/google-cloud-eventarc/google/cloud/eventarc/__init__.py index e5c5543374e0..882045fbe450 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc/__init__.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc/__init__.py @@ -27,37 +27,70 @@ FilteringAttribute, Provider, ) +from google.cloud.eventarc_v1.types.enrollment import Enrollment from google.cloud.eventarc_v1.types.eventarc import ( CreateChannelConnectionRequest, CreateChannelRequest, + CreateEnrollmentRequest, + CreateGoogleApiSourceRequest, + CreateMessageBusRequest, + CreatePipelineRequest, CreateTriggerRequest, DeleteChannelConnectionRequest, DeleteChannelRequest, + DeleteEnrollmentRequest, + DeleteGoogleApiSourceRequest, + DeleteMessageBusRequest, + DeletePipelineRequest, DeleteTriggerRequest, GetChannelConnectionRequest, GetChannelRequest, + GetEnrollmentRequest, + GetGoogleApiSourceRequest, GetGoogleChannelConfigRequest, + GetMessageBusRequest, + GetPipelineRequest, GetProviderRequest, GetTriggerRequest, ListChannelConnectionsRequest, ListChannelConnectionsResponse, ListChannelsRequest, ListChannelsResponse, + ListEnrollmentsRequest, + ListEnrollmentsResponse, + ListGoogleApiSourcesRequest, + ListGoogleApiSourcesResponse, + ListMessageBusEnrollmentsRequest, + ListMessageBusEnrollmentsResponse, + ListMessageBusesRequest, + ListMessageBusesResponse, + ListPipelinesRequest, + ListPipelinesResponse, ListProvidersRequest, ListProvidersResponse, ListTriggersRequest, ListTriggersResponse, OperationMetadata, UpdateChannelRequest, + UpdateEnrollmentRequest, + UpdateGoogleApiSourceRequest, UpdateGoogleChannelConfigRequest, + UpdateMessageBusRequest, + UpdatePipelineRequest, UpdateTriggerRequest, ) +from google.cloud.eventarc_v1.types.google_api_source import GoogleApiSource from google.cloud.eventarc_v1.types.google_channel_config import GoogleChannelConfig +from google.cloud.eventarc_v1.types.logging_config import LoggingConfig +from google.cloud.eventarc_v1.types.message_bus import MessageBus +from google.cloud.eventarc_v1.types.network_config import NetworkConfig +from google.cloud.eventarc_v1.types.pipeline import Pipeline from google.cloud.eventarc_v1.types.trigger import ( GKE, CloudRun, Destination, EventFilter, + HttpEndpoint, Pubsub, StateCondition, Transport, @@ -72,34 +105,67 @@ "EventType", "FilteringAttribute", "Provider", + "Enrollment", "CreateChannelConnectionRequest", "CreateChannelRequest", + "CreateEnrollmentRequest", + "CreateGoogleApiSourceRequest", + "CreateMessageBusRequest", + "CreatePipelineRequest", "CreateTriggerRequest", "DeleteChannelConnectionRequest", "DeleteChannelRequest", + "DeleteEnrollmentRequest", + "DeleteGoogleApiSourceRequest", + "DeleteMessageBusRequest", + "DeletePipelineRequest", "DeleteTriggerRequest", "GetChannelConnectionRequest", "GetChannelRequest", + "GetEnrollmentRequest", + "GetGoogleApiSourceRequest", "GetGoogleChannelConfigRequest", + "GetMessageBusRequest", + "GetPipelineRequest", "GetProviderRequest", "GetTriggerRequest", "ListChannelConnectionsRequest", "ListChannelConnectionsResponse", "ListChannelsRequest", "ListChannelsResponse", + "ListEnrollmentsRequest", + "ListEnrollmentsResponse", + "ListGoogleApiSourcesRequest", + "ListGoogleApiSourcesResponse", + "ListMessageBusEnrollmentsRequest", + "ListMessageBusEnrollmentsResponse", + "ListMessageBusesRequest", + "ListMessageBusesResponse", + "ListPipelinesRequest", + "ListPipelinesResponse", "ListProvidersRequest", "ListProvidersResponse", "ListTriggersRequest", "ListTriggersResponse", "OperationMetadata", "UpdateChannelRequest", + "UpdateEnrollmentRequest", + "UpdateGoogleApiSourceRequest", "UpdateGoogleChannelConfigRequest", + "UpdateMessageBusRequest", + "UpdatePipelineRequest", "UpdateTriggerRequest", + "GoogleApiSource", "GoogleChannelConfig", + "LoggingConfig", + "MessageBus", + "NetworkConfig", + "Pipeline", "CloudRun", "Destination", "EventFilter", "GKE", + "HttpEndpoint", "Pubsub", "StateCondition", "Transport", diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc/gapic_version.py b/packages/google-cloud-eventarc/google/cloud/eventarc/gapic_version.py index 739fdfae141c..43155ded0db3 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc/gapic_version.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.0" # {x-release-please-version} +__version__ = "1.13.0" # {x-release-please-version} diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/__init__.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/__init__.py index 072291c756d4..05cc85f5d8b9 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/__init__.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/__init__.py @@ -22,37 +22,70 @@ from .types.channel import Channel from .types.channel_connection import ChannelConnection from .types.discovery import EventType, FilteringAttribute, Provider +from .types.enrollment import Enrollment from .types.eventarc import ( CreateChannelConnectionRequest, CreateChannelRequest, + CreateEnrollmentRequest, + CreateGoogleApiSourceRequest, + CreateMessageBusRequest, + CreatePipelineRequest, CreateTriggerRequest, DeleteChannelConnectionRequest, DeleteChannelRequest, + DeleteEnrollmentRequest, + DeleteGoogleApiSourceRequest, + DeleteMessageBusRequest, + DeletePipelineRequest, DeleteTriggerRequest, GetChannelConnectionRequest, GetChannelRequest, + GetEnrollmentRequest, + GetGoogleApiSourceRequest, GetGoogleChannelConfigRequest, + GetMessageBusRequest, + GetPipelineRequest, GetProviderRequest, GetTriggerRequest, ListChannelConnectionsRequest, ListChannelConnectionsResponse, ListChannelsRequest, ListChannelsResponse, + ListEnrollmentsRequest, + ListEnrollmentsResponse, + ListGoogleApiSourcesRequest, + ListGoogleApiSourcesResponse, + ListMessageBusEnrollmentsRequest, + ListMessageBusEnrollmentsResponse, + ListMessageBusesRequest, + ListMessageBusesResponse, + ListPipelinesRequest, + ListPipelinesResponse, ListProvidersRequest, ListProvidersResponse, ListTriggersRequest, ListTriggersResponse, OperationMetadata, UpdateChannelRequest, + UpdateEnrollmentRequest, + UpdateGoogleApiSourceRequest, UpdateGoogleChannelConfigRequest, + UpdateMessageBusRequest, + UpdatePipelineRequest, UpdateTriggerRequest, ) +from .types.google_api_source import GoogleApiSource from .types.google_channel_config import GoogleChannelConfig +from .types.logging_config import LoggingConfig +from .types.message_bus import MessageBus +from .types.network_config import NetworkConfig +from .types.pipeline import Pipeline from .types.trigger import ( GKE, CloudRun, Destination, EventFilter, + HttpEndpoint, Pubsub, StateCondition, Transport, @@ -66,11 +99,20 @@ "CloudRun", "CreateChannelConnectionRequest", "CreateChannelRequest", + "CreateEnrollmentRequest", + "CreateGoogleApiSourceRequest", + "CreateMessageBusRequest", + "CreatePipelineRequest", "CreateTriggerRequest", "DeleteChannelConnectionRequest", "DeleteChannelRequest", + "DeleteEnrollmentRequest", + "DeleteGoogleApiSourceRequest", + "DeleteMessageBusRequest", + "DeletePipelineRequest", "DeleteTriggerRequest", "Destination", + "Enrollment", "EventFilter", "EventType", "EventarcClient", @@ -78,25 +120,49 @@ "GKE", "GetChannelConnectionRequest", "GetChannelRequest", + "GetEnrollmentRequest", + "GetGoogleApiSourceRequest", "GetGoogleChannelConfigRequest", + "GetMessageBusRequest", + "GetPipelineRequest", "GetProviderRequest", "GetTriggerRequest", + "GoogleApiSource", "GoogleChannelConfig", + "HttpEndpoint", "ListChannelConnectionsRequest", "ListChannelConnectionsResponse", "ListChannelsRequest", "ListChannelsResponse", + "ListEnrollmentsRequest", + "ListEnrollmentsResponse", + "ListGoogleApiSourcesRequest", + "ListGoogleApiSourcesResponse", + "ListMessageBusEnrollmentsRequest", + "ListMessageBusEnrollmentsResponse", + "ListMessageBusesRequest", + "ListMessageBusesResponse", + "ListPipelinesRequest", + "ListPipelinesResponse", "ListProvidersRequest", "ListProvidersResponse", "ListTriggersRequest", "ListTriggersResponse", + "LoggingConfig", + "MessageBus", + "NetworkConfig", "OperationMetadata", + "Pipeline", "Provider", "Pubsub", "StateCondition", "Transport", "Trigger", "UpdateChannelRequest", + "UpdateEnrollmentRequest", + "UpdateGoogleApiSourceRequest", "UpdateGoogleChannelConfigRequest", + "UpdateMessageBusRequest", + "UpdatePipelineRequest", "UpdateTriggerRequest", ) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_metadata.json b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_metadata.json index e56055316014..0f7262654380 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_metadata.json +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_metadata.json @@ -20,6 +20,26 @@ "create_channel_connection" ] }, + "CreateEnrollment": { + "methods": [ + "create_enrollment" + ] + }, + "CreateGoogleApiSource": { + "methods": [ + "create_google_api_source" + ] + }, + "CreateMessageBus": { + "methods": [ + "create_message_bus" + ] + }, + "CreatePipeline": { + "methods": [ + "create_pipeline" + ] + }, "CreateTrigger": { "methods": [ "create_trigger" @@ -35,6 +55,26 @@ "delete_channel_connection" ] }, + "DeleteEnrollment": { + "methods": [ + "delete_enrollment" + ] + }, + "DeleteGoogleApiSource": { + "methods": [ + "delete_google_api_source" + ] + }, + "DeleteMessageBus": { + "methods": [ + "delete_message_bus" + ] + }, + "DeletePipeline": { + "methods": [ + "delete_pipeline" + ] + }, "DeleteTrigger": { "methods": [ "delete_trigger" @@ -50,11 +90,31 @@ "get_channel_connection" ] }, + "GetEnrollment": { + "methods": [ + "get_enrollment" + ] + }, + "GetGoogleApiSource": { + "methods": [ + "get_google_api_source" + ] + }, "GetGoogleChannelConfig": { "methods": [ "get_google_channel_config" ] }, + "GetMessageBus": { + "methods": [ + "get_message_bus" + ] + }, + "GetPipeline": { + "methods": [ + "get_pipeline" + ] + }, "GetProvider": { "methods": [ "get_provider" @@ -75,6 +135,31 @@ "list_channels" ] }, + "ListEnrollments": { + "methods": [ + "list_enrollments" + ] + }, + "ListGoogleApiSources": { + "methods": [ + "list_google_api_sources" + ] + }, + "ListMessageBusEnrollments": { + "methods": [ + "list_message_bus_enrollments" + ] + }, + "ListMessageBuses": { + "methods": [ + "list_message_buses" + ] + }, + "ListPipelines": { + "methods": [ + "list_pipelines" + ] + }, "ListProviders": { "methods": [ "list_providers" @@ -90,11 +175,31 @@ "update_channel" ] }, + "UpdateEnrollment": { + "methods": [ + "update_enrollment" + ] + }, + "UpdateGoogleApiSource": { + "methods": [ + "update_google_api_source" + ] + }, "UpdateGoogleChannelConfig": { "methods": [ "update_google_channel_config" ] }, + "UpdateMessageBus": { + "methods": [ + "update_message_bus" + ] + }, + "UpdatePipeline": { + "methods": [ + "update_pipeline" + ] + }, "UpdateTrigger": { "methods": [ "update_trigger" @@ -115,6 +220,26 @@ "create_channel_connection" ] }, + "CreateEnrollment": { + "methods": [ + "create_enrollment" + ] + }, + "CreateGoogleApiSource": { + "methods": [ + "create_google_api_source" + ] + }, + "CreateMessageBus": { + "methods": [ + "create_message_bus" + ] + }, + "CreatePipeline": { + "methods": [ + "create_pipeline" + ] + }, "CreateTrigger": { "methods": [ "create_trigger" @@ -130,6 +255,26 @@ "delete_channel_connection" ] }, + "DeleteEnrollment": { + "methods": [ + "delete_enrollment" + ] + }, + "DeleteGoogleApiSource": { + "methods": [ + "delete_google_api_source" + ] + }, + "DeleteMessageBus": { + "methods": [ + "delete_message_bus" + ] + }, + "DeletePipeline": { + "methods": [ + "delete_pipeline" + ] + }, "DeleteTrigger": { "methods": [ "delete_trigger" @@ -145,11 +290,31 @@ "get_channel_connection" ] }, + "GetEnrollment": { + "methods": [ + "get_enrollment" + ] + }, + "GetGoogleApiSource": { + "methods": [ + "get_google_api_source" + ] + }, "GetGoogleChannelConfig": { "methods": [ "get_google_channel_config" ] }, + "GetMessageBus": { + "methods": [ + "get_message_bus" + ] + }, + "GetPipeline": { + "methods": [ + "get_pipeline" + ] + }, "GetProvider": { "methods": [ "get_provider" @@ -170,6 +335,31 @@ "list_channels" ] }, + "ListEnrollments": { + "methods": [ + "list_enrollments" + ] + }, + "ListGoogleApiSources": { + "methods": [ + "list_google_api_sources" + ] + }, + "ListMessageBusEnrollments": { + "methods": [ + "list_message_bus_enrollments" + ] + }, + "ListMessageBuses": { + "methods": [ + "list_message_buses" + ] + }, + "ListPipelines": { + "methods": [ + "list_pipelines" + ] + }, "ListProviders": { "methods": [ "list_providers" @@ -185,11 +375,31 @@ "update_channel" ] }, + "UpdateEnrollment": { + "methods": [ + "update_enrollment" + ] + }, + "UpdateGoogleApiSource": { + "methods": [ + "update_google_api_source" + ] + }, "UpdateGoogleChannelConfig": { "methods": [ "update_google_channel_config" ] }, + "UpdateMessageBus": { + "methods": [ + "update_message_bus" + ] + }, + "UpdatePipeline": { + "methods": [ + "update_pipeline" + ] + }, "UpdateTrigger": { "methods": [ "update_trigger" @@ -210,6 +420,26 @@ "create_channel_connection" ] }, + "CreateEnrollment": { + "methods": [ + "create_enrollment" + ] + }, + "CreateGoogleApiSource": { + "methods": [ + "create_google_api_source" + ] + }, + "CreateMessageBus": { + "methods": [ + "create_message_bus" + ] + }, + "CreatePipeline": { + "methods": [ + "create_pipeline" + ] + }, "CreateTrigger": { "methods": [ "create_trigger" @@ -225,6 +455,26 @@ "delete_channel_connection" ] }, + "DeleteEnrollment": { + "methods": [ + "delete_enrollment" + ] + }, + "DeleteGoogleApiSource": { + "methods": [ + "delete_google_api_source" + ] + }, + "DeleteMessageBus": { + "methods": [ + "delete_message_bus" + ] + }, + "DeletePipeline": { + "methods": [ + "delete_pipeline" + ] + }, "DeleteTrigger": { "methods": [ "delete_trigger" @@ -240,11 +490,31 @@ "get_channel_connection" ] }, + "GetEnrollment": { + "methods": [ + "get_enrollment" + ] + }, + "GetGoogleApiSource": { + "methods": [ + "get_google_api_source" + ] + }, "GetGoogleChannelConfig": { "methods": [ "get_google_channel_config" ] }, + "GetMessageBus": { + "methods": [ + "get_message_bus" + ] + }, + "GetPipeline": { + "methods": [ + "get_pipeline" + ] + }, "GetProvider": { "methods": [ "get_provider" @@ -265,6 +535,31 @@ "list_channels" ] }, + "ListEnrollments": { + "methods": [ + "list_enrollments" + ] + }, + "ListGoogleApiSources": { + "methods": [ + "list_google_api_sources" + ] + }, + "ListMessageBusEnrollments": { + "methods": [ + "list_message_bus_enrollments" + ] + }, + "ListMessageBuses": { + "methods": [ + "list_message_buses" + ] + }, + "ListPipelines": { + "methods": [ + "list_pipelines" + ] + }, "ListProviders": { "methods": [ "list_providers" @@ -280,11 +575,31 @@ "update_channel" ] }, + "UpdateEnrollment": { + "methods": [ + "update_enrollment" + ] + }, + "UpdateGoogleApiSource": { + "methods": [ + "update_google_api_source" + ] + }, "UpdateGoogleChannelConfig": { "methods": [ "update_google_channel_config" ] }, + "UpdateMessageBus": { + "methods": [ + "update_message_bus" + ] + }, + "UpdatePipeline": { + "methods": [ + "update_pipeline" + ] + }, "UpdateTrigger": { "methods": [ "update_trigger" diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_version.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_version.py index 739fdfae141c..43155ded0db3 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_version.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.0" # {x-release-please-version} +__version__ = "1.13.0" # {x-release-please-version} diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py index 821859fa0f4b..d1f50a061562 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/async_client.py @@ -53,14 +53,24 @@ from google.cloud.eventarc_v1.services.eventarc import pagers from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import channel from google.cloud.eventarc_v1.types import channel as gce_channel from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery, eventarc +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import logging_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import pipeline as gce_pipeline from google.cloud.eventarc_v1.types import trigger from google.cloud.eventarc_v1.types import trigger as gce_trigger @@ -94,16 +104,32 @@ class EventarcAsyncClient: parse_cloud_function_path = staticmethod(EventarcClient.parse_cloud_function_path) crypto_key_path = staticmethod(EventarcClient.crypto_key_path) parse_crypto_key_path = staticmethod(EventarcClient.parse_crypto_key_path) + enrollment_path = staticmethod(EventarcClient.enrollment_path) + parse_enrollment_path = staticmethod(EventarcClient.parse_enrollment_path) + google_api_source_path = staticmethod(EventarcClient.google_api_source_path) + parse_google_api_source_path = staticmethod( + EventarcClient.parse_google_api_source_path + ) google_channel_config_path = staticmethod(EventarcClient.google_channel_config_path) parse_google_channel_config_path = staticmethod( EventarcClient.parse_google_channel_config_path ) + message_bus_path = staticmethod(EventarcClient.message_bus_path) + parse_message_bus_path = staticmethod(EventarcClient.parse_message_bus_path) + network_attachment_path = staticmethod(EventarcClient.network_attachment_path) + parse_network_attachment_path = staticmethod( + EventarcClient.parse_network_attachment_path + ) + pipeline_path = staticmethod(EventarcClient.pipeline_path) + parse_pipeline_path = staticmethod(EventarcClient.parse_pipeline_path) provider_path = staticmethod(EventarcClient.provider_path) parse_provider_path = staticmethod(EventarcClient.parse_provider_path) service_path = staticmethod(EventarcClient.service_path) parse_service_path = staticmethod(EventarcClient.parse_service_path) service_account_path = staticmethod(EventarcClient.service_account_path) parse_service_account_path = staticmethod(EventarcClient.parse_service_account_path) + topic_path = staticmethod(EventarcClient.topic_path) + parse_topic_path = staticmethod(EventarcClient.parse_topic_path) trigger_path = staticmethod(EventarcClient.trigger_path) parse_trigger_path = staticmethod(EventarcClient.parse_trigger_path) workflow_path = staticmethod(EventarcClient.workflow_path) @@ -557,7 +583,6 @@ async def sample_create_trigger(): parent="parent_value", trigger=trigger, trigger_id="trigger_id_value", - validate_only=True, ) # Make the request @@ -696,7 +721,6 @@ async def sample_update_trigger(): # Initialize request argument(s) request = eventarc_v1.UpdateTriggerRequest( - validate_only=True, ) # Make the request @@ -840,7 +864,6 @@ async def sample_delete_trigger(): # Initialize request argument(s) request = eventarc_v1.DeleteTriggerRequest( name="name_value", - validate_only=True, ) # Make the request @@ -1213,7 +1236,6 @@ async def sample_create_channel(): parent="parent_value", channel=channel, channel_id="channel_id_value", - validate_only=True, ) # Make the request @@ -1354,7 +1376,6 @@ async def sample_update_channel(): # Initialize request argument(s) request = eventarc_v1.UpdateChannelRequest( - validate_only=True, ) # Make the request @@ -1490,7 +1511,6 @@ async def sample_delete_channel(): # Initialize request argument(s) request = eventarc_v1.DeleteChannelRequest( name="name_value", - validate_only=True, ) # Make the request @@ -2560,6 +2580,2721 @@ async def sample_update_google_channel_config(): # Done; return the response. return response + async def get_message_bus( + self, + request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message_bus.MessageBus: + r"""Get a single MessageBus. + + .. 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 eventarc_v1 + + async def sample_get_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetMessageBusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_message_bus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetMessageBusRequest, dict]]): + The request object. The request message for the + GetMessageBus method. + name (:class:`str`): + Required. The name of the message bus + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.MessageBus: + MessageBus for the messages flowing + through the system. The admin has + visibility and control over the messages + being published and consumed and can + restrict publishers and subscribers to + only a subset of data available in the + system by defining authorization + policies. + + """ + # 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. + has_flattened_params = any([name]) + 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, eventarc.GetMessageBusRequest): + request = eventarc.GetMessageBusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_message_bus + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_message_buses( + self, + request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessageBusesAsyncPager: + r"""List message buses. + + .. 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 eventarc_v1 + + async def sample_list_message_buses(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_buses(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListMessageBusesRequest, dict]]): + The request object. The request message for the + ListMessageBuses method. + parent (:class:`str`): + Required. The parent collection to + list triggers on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesAsyncPager: + The response message for the ListMessageBuses method. + + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListMessageBusesRequest): + request = eventarc.ListMessageBusesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_message_buses + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMessageBusesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_message_bus_enrollments( + self, + request: Optional[ + Union[eventarc.ListMessageBusEnrollmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessageBusEnrollmentsAsyncPager: + r"""List message bus enrollments. + + .. 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 eventarc_v1 + + async def sample_list_message_bus_enrollments(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_bus_enrollments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest, dict]]): + The request object. The request message for the + ``ListMessageBusEnrollments`` method. + parent (:class:`str`): + Required. The parent message bus to + list enrollments on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsAsyncPager: + The response message for the ListMessageBusEnrollments + method.\` + + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListMessageBusEnrollmentsRequest): + request = eventarc.ListMessageBusEnrollmentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_message_bus_enrollments + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMessageBusEnrollmentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_message_bus( + self, + request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_bus: Optional[gce_message_bus.MessageBus] = None, + message_bus_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new MessageBus in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Make the request + operation = client.create_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateMessageBusRequest, dict]]): + The request object. The request message for the + CreateMessageBus method. + parent (:class:`str`): + Required. The parent collection in + which to add this message bus. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_bus (:class:`google.cloud.eventarc_v1.types.MessageBus`): + Required. The message bus to create. + This corresponds to the ``message_bus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_bus_id (:class:`str`): + Required. The user-provided ID to be assigned to the + MessageBus. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + + This corresponds to the ``message_bus_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # 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. + has_flattened_params = any([parent, message_bus, message_bus_id]) + 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, eventarc.CreateMessageBusRequest): + request = eventarc.CreateMessageBusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message_bus is not None: + request.message_bus = message_bus + if message_bus_id is not None: + request.message_bus_id = message_bus_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_message_bus + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gce_message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_message_bus( + self, + request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, + *, + message_bus: Optional[gce_message_bus.MessageBus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single message bus. + + .. 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 eventarc_v1 + + async def sample_update_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateMessageBusRequest( + ) + + # Make the request + operation = client.update_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateMessageBusRequest, dict]]): + The request object. The request message for the + UpdateMessageBus method. + message_bus (:class:`google.cloud.eventarc_v1.types.MessageBus`): + Required. The MessageBus to be + updated. + + This corresponds to the ``message_bus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # 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. + has_flattened_params = any([message_bus, update_mask]) + 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, eventarc.UpdateMessageBusRequest): + request = eventarc.UpdateMessageBusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if message_bus is not None: + request.message_bus = message_bus + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_message_bus + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("message_bus.name", request.message_bus.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gce_message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_message_bus( + self, + request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single message bus. + + .. 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 eventarc_v1 + + async def sample_delete_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteMessageBusRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteMessageBusRequest, dict]]): + The request object. The request message for the + DeleteMessageBus method. + name (:class:`str`): + Required. The name of the MessageBus + to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Optional. If provided, the MessageBus + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # 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. + has_flattened_params = any([name, etag]) + 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, eventarc.DeleteMessageBusRequest): + request = eventarc.DeleteMessageBusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_message_bus + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_enrollment( + self, + request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> enrollment.Enrollment: + r"""Get a single Enrollment. + + .. 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 eventarc_v1 + + async def sample_get_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetEnrollmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_enrollment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetEnrollmentRequest, dict]]): + The request object. The request message for the + GetEnrollment method. + name (:class:`str`): + Required. The name of the Enrollment + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Enrollment: + An enrollment represents a + subscription for messages on a + particular message bus. It defines a + matching criteria for messages on the + bus and the subscriber endpoint where + matched messages should be delivered. + + """ + # 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. + has_flattened_params = any([name]) + 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, eventarc.GetEnrollmentRequest): + request = eventarc.GetEnrollmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_enrollment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_enrollments( + self, + request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnrollmentsAsyncPager: + r"""List Enrollments. + + .. 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 eventarc_v1 + + async def sample_list_enrollments(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_enrollments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListEnrollmentsRequest, dict]]): + The request object. The request message for the + ListEnrollments method. + parent (:class:`str`): + Required. The parent collection to + list triggers on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsAsyncPager: + The response message for the ListEnrollments method. + + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListEnrollmentsRequest): + request = eventarc.ListEnrollmentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_enrollments + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEnrollmentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_enrollment( + self, + request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + enrollment: Optional[gce_enrollment.Enrollment] = None, + enrollment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new Enrollment in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.CreateEnrollmentRequest( + parent="parent_value", + enrollment=enrollment, + enrollment_id="enrollment_id_value", + ) + + # Make the request + operation = client.create_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateEnrollmentRequest, dict]]): + The request object. The request message for the + CreateEnrollment method. + parent (:class:`str`): + Required. The parent collection in + which to add this enrollment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enrollment (:class:`google.cloud.eventarc_v1.types.Enrollment`): + Required. The enrollment to create. + This corresponds to the ``enrollment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enrollment_id (:class:`str`): + Required. The user-provided ID to be assigned to the + Enrollment. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + + This corresponds to the ``enrollment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # 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. + has_flattened_params = any([parent, enrollment, enrollment_id]) + 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, eventarc.CreateEnrollmentRequest): + request = eventarc.CreateEnrollmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if enrollment is not None: + request.enrollment = enrollment + if enrollment_id is not None: + request.enrollment_id = enrollment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_enrollment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gce_enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_enrollment( + self, + request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, + *, + enrollment: Optional[gce_enrollment.Enrollment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single Enrollment. + + .. 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 eventarc_v1 + + async def sample_update_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.UpdateEnrollmentRequest( + enrollment=enrollment, + ) + + # Make the request + operation = client.update_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateEnrollmentRequest, dict]]): + The request object. The request message for the + UpdateEnrollment method. + enrollment (:class:`google.cloud.eventarc_v1.types.Enrollment`): + Required. The Enrollment to be + updated. + + This corresponds to the ``enrollment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # 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. + has_flattened_params = any([enrollment, update_mask]) + 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, eventarc.UpdateEnrollmentRequest): + request = eventarc.UpdateEnrollmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if enrollment is not None: + request.enrollment = enrollment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_enrollment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("enrollment.name", request.enrollment.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gce_enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_enrollment( + self, + request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single Enrollment. + + .. 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 eventarc_v1 + + async def sample_delete_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteEnrollmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteEnrollmentRequest, dict]]): + The request object. The request message for the + DeleteEnrollment method. + name (:class:`str`): + Required. The name of the Enrollment + to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Optional. If provided, the Enrollment + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # 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. + has_flattened_params = any([name, etag]) + 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, eventarc.DeleteEnrollmentRequest): + request = eventarc.DeleteEnrollmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_enrollment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_pipeline( + self, + request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pipeline.Pipeline: + r"""Get a single Pipeline. + + .. 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 eventarc_v1 + + async def sample_get_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetPipelineRequest( + name="name_value", + ) + + # Make the request + response = await client.get_pipeline(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetPipelineRequest, dict]]): + The request object. The request message for the + GetPipeline method. + name (:class:`str`): + Required. The name of the pipeline to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Pipeline: + A representation of the Pipeline + 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. + has_flattened_params = any([name]) + 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, eventarc.GetPipelineRequest): + request = eventarc.GetPipelineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_pipeline + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_pipelines( + self, + request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPipelinesAsyncPager: + r"""List pipelines. + + .. 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 eventarc_v1 + + async def sample_list_pipelines(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListPipelinesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_pipelines(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListPipelinesRequest, dict]]): + The request object. The request message for the + ListPipelines method. + parent (:class:`str`): + Required. The parent collection to + list pipelines on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesAsyncPager: + The response message for the + ListPipelines method. + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListPipelinesRequest): + request = eventarc.ListPipelinesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_pipelines + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPipelinesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_pipeline( + self, + request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, + *, + parent: Optional[str] = None, + pipeline: Optional[gce_pipeline.Pipeline] = None, + pipeline_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new Pipeline in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.CreatePipelineRequest( + parent="parent_value", + pipeline=pipeline, + pipeline_id="pipeline_id_value", + ) + + # Make the request + operation = client.create_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreatePipelineRequest, dict]]): + The request object. The request message for the + CreatePipeline method. + parent (:class:`str`): + Required. The parent collection in + which to add this pipeline. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pipeline (:class:`google.cloud.eventarc_v1.types.Pipeline`): + Required. The pipeline to create. + This corresponds to the ``pipeline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pipeline_id (:class:`str`): + Required. The user-provided ID to be + assigned to the Pipeline. + + This corresponds to the ``pipeline_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline 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. + has_flattened_params = any([parent, pipeline, pipeline_id]) + 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, eventarc.CreatePipelineRequest): + request = eventarc.CreatePipelineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if pipeline is not None: + request.pipeline = pipeline + if pipeline_id is not None: + request.pipeline_id = pipeline_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_pipeline + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gce_pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_pipeline( + self, + request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, + *, + pipeline: Optional[gce_pipeline.Pipeline] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single pipeline. + + .. 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 eventarc_v1 + + async def sample_update_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.UpdatePipelineRequest( + pipeline=pipeline, + ) + + # Make the request + operation = client.update_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdatePipelineRequest, dict]]): + The request object. The request message for the + UpdatePipeline method. + pipeline (:class:`google.cloud.eventarc_v1.types.Pipeline`): + Required. The Pipeline to be updated. + This corresponds to the ``pipeline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline 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. + has_flattened_params = any([pipeline, update_mask]) + 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, eventarc.UpdatePipelineRequest): + request = eventarc.UpdatePipelineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if pipeline is not None: + request.pipeline = pipeline + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_pipeline + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("pipeline.name", request.pipeline.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gce_pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_pipeline( + self, + request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single pipeline. + + .. 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 eventarc_v1 + + async def sample_delete_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeletePipelineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeletePipelineRequest, dict]]): + The request object. The request message for the + DeletePipeline method. + name (:class:`str`): + Required. The name of the Pipeline to + be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Optional. If provided, the Pipeline + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline 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. + has_flattened_params = any([name, etag]) + 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, eventarc.DeletePipelineRequest): + request = eventarc.DeletePipelineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_pipeline + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_google_api_source( + self, + request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> google_api_source.GoogleApiSource: + r"""Get a single GoogleApiSource. + + .. 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 eventarc_v1 + + async def sample_get_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_google_api_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest, dict]]): + The request object. The request message for the + GetGoogleApiSource method. + name (:class:`str`): + Required. The name of the google api + source to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.GoogleApiSource: + A GoogleApiSource represents a + subscription of 1P events from a + MessageBus. + + """ + # 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. + has_flattened_params = any([name]) + 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, eventarc.GetGoogleApiSourceRequest): + request = eventarc.GetGoogleApiSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_google_api_source + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_google_api_sources( + self, + request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGoogleApiSourcesAsyncPager: + r"""List GoogleApiSources. + + .. 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 eventarc_v1 + + async def sample_list_google_api_sources(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListGoogleApiSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_api_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest, dict]]): + The request object. The request message for the + ListGoogleApiSources method. + parent (:class:`str`): + Required. The parent collection to + list GoogleApiSources on. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesAsyncPager: + The response message for the ListGoogleApiSources + method. + + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListGoogleApiSourcesRequest): + request = eventarc.ListGoogleApiSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_google_api_sources + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListGoogleApiSourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_google_api_source( + self, + request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + google_api_source_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create a new GoogleApiSource in a particular project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + async def sample_create_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source=google_api_source, + google_api_source_id="google_api_source_id_value", + ) + + # Make the request + operation = client.create_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest, dict]]): + The request object. The request message for the + CreateGoogleApiSource method. + parent (:class:`str`): + Required. The parent collection in + which to add this google api source. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_api_source (:class:`google.cloud.eventarc_v1.types.GoogleApiSource`): + Required. The google api source to + create. + + This corresponds to the ``google_api_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_api_source_id (:class:`str`): + Required. The user-provided ID to be assigned to the + GoogleApiSource. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + + This corresponds to the ``google_api_source_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # 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. + has_flattened_params = any([parent, google_api_source, google_api_source_id]) + 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, eventarc.CreateGoogleApiSourceRequest): + request = eventarc.CreateGoogleApiSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if google_api_source is not None: + request.google_api_source = google_api_source + if google_api_source_id is not None: + request.google_api_source_id = google_api_source_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_google_api_source + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gce_google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_google_api_source( + self, + request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, + *, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update a single GoogleApiSource. + + .. 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 eventarc_v1 + + async def sample_update_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.UpdateGoogleApiSourceRequest( + google_api_source=google_api_source, + ) + + # Make the request + operation = client.update_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest, dict]]): + The request object. The request message for the + UpdateGoogleApiSource method. + google_api_source (:class:`google.cloud.eventarc_v1.types.GoogleApiSource`): + Required. The GoogleApiSource to be + updated. + + This corresponds to the ``google_api_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # 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. + has_flattened_params = any([google_api_source, update_mask]) + 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, eventarc.UpdateGoogleApiSourceRequest): + request = eventarc.UpdateGoogleApiSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_api_source is not None: + request.google_api_source = google_api_source + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_google_api_source + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("google_api_source.name", request.google_api_source.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gce_google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_google_api_source( + self, + request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete a single GoogleApiSource. + + .. 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 eventarc_v1 + + async def sample_delete_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest, dict]]): + The request object. The request message for the + DeleteGoogleApiSource method. + name (:class:`str`): + Required. The name of the + GoogleApiSource to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (:class:`str`): + Optional. If provided, the MessageBus + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # 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. + has_flattened_params = any([name, etag]) + 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, eventarc.DeleteGoogleApiSourceRequest): + request = eventarc.DeleteGoogleApiSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_google_api_source + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index e31fc08752ae..f179bb2e513f 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -59,14 +59,24 @@ from google.cloud.eventarc_v1.services.eventarc import pagers from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import channel from google.cloud.eventarc_v1.types import channel as gce_channel from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery, eventarc +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import logging_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import pipeline as gce_pipeline from google.cloud.eventarc_v1.types import trigger from google.cloud.eventarc_v1.types import trigger as gce_trigger @@ -293,6 +303,52 @@ def parse_crypto_key_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def enrollment_path( + project: str, + location: str, + enrollment: str, + ) -> str: + """Returns a fully-qualified enrollment string.""" + return ( + "projects/{project}/locations/{location}/enrollments/{enrollment}".format( + project=project, + location=location, + enrollment=enrollment, + ) + ) + + @staticmethod + def parse_enrollment_path(path: str) -> Dict[str, str]: + """Parses a enrollment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/enrollments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def google_api_source_path( + project: str, + location: str, + google_api_source: str, + ) -> str: + """Returns a fully-qualified google_api_source string.""" + return "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format( + project=project, + location=location, + google_api_source=google_api_source, + ) + + @staticmethod + def parse_google_api_source_path(path: str) -> Dict[str, str]: + """Parses a google_api_source path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/googleApiSources/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def google_channel_config_path( project: str, @@ -313,6 +369,74 @@ def parse_google_channel_config_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def message_bus_path( + project: str, + location: str, + message_bus: str, + ) -> str: + """Returns a fully-qualified message_bus string.""" + return ( + "projects/{project}/locations/{location}/messageBuses/{message_bus}".format( + project=project, + location=location, + message_bus=message_bus, + ) + ) + + @staticmethod + def parse_message_bus_path(path: str) -> Dict[str, str]: + """Parses a message_bus path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/messageBuses/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def network_attachment_path( + project: str, + region: str, + networkattachment: str, + ) -> str: + """Returns a fully-qualified network_attachment string.""" + return "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format( + project=project, + region=region, + networkattachment=networkattachment, + ) + + @staticmethod + def parse_network_attachment_path(path: str) -> Dict[str, str]: + """Parses a network_attachment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def pipeline_path( + project: str, + location: str, + pipeline: str, + ) -> str: + """Returns a fully-qualified pipeline string.""" + return "projects/{project}/locations/{location}/pipelines/{pipeline}".format( + project=project, + location=location, + pipeline=pipeline, + ) + + @staticmethod + def parse_pipeline_path(path: str) -> Dict[str, str]: + """Parses a pipeline path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/pipelines/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def provider_path( project: str, @@ -366,6 +490,23 @@ def parse_service_account_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def topic_path( + project: str, + topic: str, + ) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str, str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + @staticmethod def trigger_path( project: str, @@ -1140,7 +1281,6 @@ def sample_create_trigger(): parent="parent_value", trigger=trigger, trigger_id="trigger_id_value", - validate_only=True, ) # Make the request @@ -1276,7 +1416,6 @@ def sample_update_trigger(): # Initialize request argument(s) request = eventarc_v1.UpdateTriggerRequest( - validate_only=True, ) # Make the request @@ -1417,7 +1556,6 @@ def sample_delete_trigger(): # Initialize request argument(s) request = eventarc_v1.DeleteTriggerRequest( name="name_value", - validate_only=True, ) # Make the request @@ -1781,7 +1919,6 @@ def sample_create_channel(): parent="parent_value", channel=channel, channel_id="channel_id_value", - validate_only=True, ) # Make the request @@ -1919,7 +2056,6 @@ def sample_update_channel(): # Initialize request argument(s) request = eventarc_v1.UpdateChannelRequest( - validate_only=True, ) # Make the request @@ -2052,7 +2188,6 @@ def sample_delete_channel(): # Initialize request argument(s) request = eventarc_v1.DeleteChannelRequest( name="name_value", - validate_only=True, ) # Make the request @@ -3103,6 +3238,2660 @@ def sample_update_google_channel_config(): # Done; return the response. return response + def get_message_bus( + self, + request: Optional[Union[eventarc.GetMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message_bus.MessageBus: + r"""Get a single MessageBus. + + .. 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 eventarc_v1 + + def sample_get_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetMessageBusRequest( + name="name_value", + ) + + # Make the request + response = client.get_message_bus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetMessageBusRequest, dict]): + The request object. The request message for the + GetMessageBus method. + name (str): + Required. The name of the message bus + to get. + + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.MessageBus: + MessageBus for the messages flowing + through the system. The admin has + visibility and control over the messages + being published and consumed and can + restrict publishers and subscribers to + only a subset of data available in the + system by defining authorization + policies. + + """ + # 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. + has_flattened_params = any([name]) + 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, eventarc.GetMessageBusRequest): + request = eventarc.GetMessageBusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_message_bus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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_message_buses( + self, + request: Optional[Union[eventarc.ListMessageBusesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessageBusesPager: + r"""List message buses. + + .. 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 eventarc_v1 + + def sample_list_message_buses(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_buses(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListMessageBusesRequest, dict]): + The request object. The request message for the + ListMessageBuses method. + parent (str): + Required. The parent collection to + list triggers on. + + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesPager: + The response message for the ListMessageBuses method. + + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListMessageBusesRequest): + request = eventarc.ListMessageBusesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_message_buses] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMessageBusesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_message_bus_enrollments( + self, + request: Optional[ + Union[eventarc.ListMessageBusEnrollmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListMessageBusEnrollmentsPager: + r"""List message bus enrollments. + + .. 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 eventarc_v1 + + def sample_list_message_bus_enrollments(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_bus_enrollments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest, dict]): + The request object. The request message for the + ``ListMessageBusEnrollments`` method. + parent (str): + Required. The parent message bus to + list enrollments on. + + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsPager: + The response message for the ListMessageBusEnrollments + method.\` + + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListMessageBusEnrollmentsRequest): + request = eventarc.ListMessageBusEnrollmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_message_bus_enrollments + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMessageBusEnrollmentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_message_bus( + self, + request: Optional[Union[eventarc.CreateMessageBusRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_bus: Optional[gce_message_bus.MessageBus] = None, + message_bus_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new MessageBus in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Make the request + operation = client.create_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateMessageBusRequest, dict]): + The request object. The request message for the + CreateMessageBus method. + parent (str): + Required. The parent collection in + which to add this message bus. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_bus (google.cloud.eventarc_v1.types.MessageBus): + Required. The message bus to create. + This corresponds to the ``message_bus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_bus_id (str): + Required. The user-provided ID to be assigned to the + MessageBus. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + + This corresponds to the ``message_bus_id`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # 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. + has_flattened_params = any([parent, message_bus, message_bus_id]) + 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, eventarc.CreateMessageBusRequest): + request = eventarc.CreateMessageBusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message_bus is not None: + request.message_bus = message_bus + if message_bus_id is not None: + request.message_bus_id = message_bus_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_message_bus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gce_message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_message_bus( + self, + request: Optional[Union[eventarc.UpdateMessageBusRequest, dict]] = None, + *, + message_bus: Optional[gce_message_bus.MessageBus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single message bus. + + .. 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 eventarc_v1 + + def sample_update_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateMessageBusRequest( + ) + + # Make the request + operation = client.update_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateMessageBusRequest, dict]): + The request object. The request message for the + UpdateMessageBus method. + message_bus (google.cloud.eventarc_v1.types.MessageBus): + Required. The MessageBus to be + updated. + + This corresponds to the ``message_bus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # 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. + has_flattened_params = any([message_bus, update_mask]) + 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, eventarc.UpdateMessageBusRequest): + request = eventarc.UpdateMessageBusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if message_bus is not None: + request.message_bus = message_bus + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_message_bus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("message_bus.name", request.message_bus.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gce_message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_message_bus( + self, + request: Optional[Union[eventarc.DeleteMessageBusRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single message bus. + + .. 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 eventarc_v1 + + def sample_delete_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteMessageBusRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteMessageBusRequest, dict]): + The request object. The request message for the + DeleteMessageBus method. + name (str): + Required. The name of the MessageBus + to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (str): + Optional. If provided, the MessageBus + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.MessageBus` MessageBus for the messages flowing through the system. The admin has + visibility and control over the messages being + published and consumed and can restrict publishers + and subscribers to only a subset of data available in + the system by defining authorization policies. + + """ + # 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. + has_flattened_params = any([name, etag]) + 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, eventarc.DeleteMessageBusRequest): + request = eventarc.DeleteMessageBusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_message_bus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + message_bus.MessageBus, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_enrollment( + self, + request: Optional[Union[eventarc.GetEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> enrollment.Enrollment: + r"""Get a single Enrollment. + + .. 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 eventarc_v1 + + def sample_get_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetEnrollmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_enrollment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetEnrollmentRequest, dict]): + The request object. The request message for the + GetEnrollment method. + name (str): + Required. The name of the Enrollment + to get. + + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Enrollment: + An enrollment represents a + subscription for messages on a + particular message bus. It defines a + matching criteria for messages on the + bus and the subscriber endpoint where + matched messages should be delivered. + + """ + # 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. + has_flattened_params = any([name]) + 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, eventarc.GetEnrollmentRequest): + request = eventarc.GetEnrollmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_enrollment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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_enrollments( + self, + request: Optional[Union[eventarc.ListEnrollmentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnrollmentsPager: + r"""List Enrollments. + + .. 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 eventarc_v1 + + def sample_list_enrollments(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_enrollments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListEnrollmentsRequest, dict]): + The request object. The request message for the + ListEnrollments method. + parent (str): + Required. The parent collection to + list triggers on. + + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsPager: + The response message for the ListEnrollments method. + + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListEnrollmentsRequest): + request = eventarc.ListEnrollmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_enrollments] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEnrollmentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_enrollment( + self, + request: Optional[Union[eventarc.CreateEnrollmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + enrollment: Optional[gce_enrollment.Enrollment] = None, + enrollment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new Enrollment in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.CreateEnrollmentRequest( + parent="parent_value", + enrollment=enrollment, + enrollment_id="enrollment_id_value", + ) + + # Make the request + operation = client.create_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateEnrollmentRequest, dict]): + The request object. The request message for the + CreateEnrollment method. + parent (str): + Required. The parent collection in + which to add this enrollment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enrollment (google.cloud.eventarc_v1.types.Enrollment): + Required. The enrollment to create. + This corresponds to the ``enrollment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + enrollment_id (str): + Required. The user-provided ID to be assigned to the + Enrollment. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + + This corresponds to the ``enrollment_id`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # 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. + has_flattened_params = any([parent, enrollment, enrollment_id]) + 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, eventarc.CreateEnrollmentRequest): + request = eventarc.CreateEnrollmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if enrollment is not None: + request.enrollment = enrollment + if enrollment_id is not None: + request.enrollment_id = enrollment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_enrollment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gce_enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_enrollment( + self, + request: Optional[Union[eventarc.UpdateEnrollmentRequest, dict]] = None, + *, + enrollment: Optional[gce_enrollment.Enrollment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single Enrollment. + + .. 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 eventarc_v1 + + def sample_update_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.UpdateEnrollmentRequest( + enrollment=enrollment, + ) + + # Make the request + operation = client.update_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateEnrollmentRequest, dict]): + The request object. The request message for the + UpdateEnrollment method. + enrollment (google.cloud.eventarc_v1.types.Enrollment): + Required. The Enrollment to be + updated. + + This corresponds to the ``enrollment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # 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. + has_flattened_params = any([enrollment, update_mask]) + 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, eventarc.UpdateEnrollmentRequest): + request = eventarc.UpdateEnrollmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if enrollment is not None: + request.enrollment = enrollment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_enrollment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("enrollment.name", request.enrollment.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gce_enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_enrollment( + self, + request: Optional[Union[eventarc.DeleteEnrollmentRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single Enrollment. + + .. 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 eventarc_v1 + + def sample_delete_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteEnrollmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteEnrollmentRequest, dict]): + The request object. The request message for the + DeleteEnrollment method. + name (str): + Required. The name of the Enrollment + to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (str): + Optional. If provided, the Enrollment + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.eventarc_v1.types.Enrollment` An enrollment represents a subscription for messages on a particular message + bus. It defines a matching criteria for messages on + the bus and the subscriber endpoint where matched + messages should be delivered. + + """ + # 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. + has_flattened_params = any([name, etag]) + 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, eventarc.DeleteEnrollmentRequest): + request = eventarc.DeleteEnrollmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_enrollment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + enrollment.Enrollment, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_pipeline( + self, + request: Optional[Union[eventarc.GetPipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pipeline.Pipeline: + r"""Get a single Pipeline. + + .. 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 eventarc_v1 + + def sample_get_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetPipelineRequest( + name="name_value", + ) + + # Make the request + response = client.get_pipeline(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetPipelineRequest, dict]): + The request object. The request message for the + GetPipeline method. + name (str): + Required. The name of the pipeline to + get. + + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.Pipeline: + A representation of the Pipeline + 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. + has_flattened_params = any([name]) + 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, eventarc.GetPipelineRequest): + request = eventarc.GetPipelineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_pipeline] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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_pipelines( + self, + request: Optional[Union[eventarc.ListPipelinesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPipelinesPager: + r"""List pipelines. + + .. 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 eventarc_v1 + + def sample_list_pipelines(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListPipelinesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_pipelines(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListPipelinesRequest, dict]): + The request object. The request message for the + ListPipelines method. + parent (str): + Required. The parent collection to + list pipelines on. + + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesPager: + The response message for the + ListPipelines method. + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListPipelinesRequest): + request = eventarc.ListPipelinesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_pipelines] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPipelinesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_pipeline( + self, + request: Optional[Union[eventarc.CreatePipelineRequest, dict]] = None, + *, + parent: Optional[str] = None, + pipeline: Optional[gce_pipeline.Pipeline] = None, + pipeline_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new Pipeline in a particular project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.CreatePipelineRequest( + parent="parent_value", + pipeline=pipeline, + pipeline_id="pipeline_id_value", + ) + + # Make the request + operation = client.create_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreatePipelineRequest, dict]): + The request object. The request message for the + CreatePipeline method. + parent (str): + Required. The parent collection in + which to add this pipeline. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pipeline (google.cloud.eventarc_v1.types.Pipeline): + Required. The pipeline to create. + This corresponds to the ``pipeline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pipeline_id (str): + Required. The user-provided ID to be + assigned to the Pipeline. + + This corresponds to the ``pipeline_id`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline 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. + has_flattened_params = any([parent, pipeline, pipeline_id]) + 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, eventarc.CreatePipelineRequest): + request = eventarc.CreatePipelineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if pipeline is not None: + request.pipeline = pipeline + if pipeline_id is not None: + request.pipeline_id = pipeline_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_pipeline] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gce_pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_pipeline( + self, + request: Optional[Union[eventarc.UpdatePipelineRequest, dict]] = None, + *, + pipeline: Optional[gce_pipeline.Pipeline] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single pipeline. + + .. 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 eventarc_v1 + + def sample_update_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.UpdatePipelineRequest( + pipeline=pipeline, + ) + + # Make the request + operation = client.update_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdatePipelineRequest, dict]): + The request object. The request message for the + UpdatePipeline method. + pipeline (google.cloud.eventarc_v1.types.Pipeline): + Required. The Pipeline to be updated. + This corresponds to the ``pipeline`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline 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. + has_flattened_params = any([pipeline, update_mask]) + 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, eventarc.UpdatePipelineRequest): + request = eventarc.UpdatePipelineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if pipeline is not None: + request.pipeline = pipeline + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_pipeline] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("pipeline.name", request.pipeline.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gce_pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_pipeline( + self, + request: Optional[Union[eventarc.DeletePipelineRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single pipeline. + + .. 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 eventarc_v1 + + def sample_delete_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeletePipelineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeletePipelineRequest, dict]): + The request object. The request message for the + DeletePipeline method. + name (str): + Required. The name of the Pipeline to + be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (str): + Optional. If provided, the Pipeline + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.Pipeline` A + representation of the Pipeline 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. + has_flattened_params = any([name, etag]) + 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, eventarc.DeletePipelineRequest): + request = eventarc.DeletePipelineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_pipeline] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + pipeline.Pipeline, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_google_api_source( + self, + request: Optional[Union[eventarc.GetGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> google_api_source.GoogleApiSource: + r"""Get a single GoogleApiSource. + + .. 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 eventarc_v1 + + def sample_get_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_google_api_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest, dict]): + The request object. The request message for the + GetGoogleApiSource method. + name (str): + Required. The name of the google api + source to get. + + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.types.GoogleApiSource: + A GoogleApiSource represents a + subscription of 1P events from a + MessageBus. + + """ + # 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. + has_flattened_params = any([name]) + 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, eventarc.GetGoogleApiSourceRequest): + request = eventarc.GetGoogleApiSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_google_api_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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_google_api_sources( + self, + request: Optional[Union[eventarc.ListGoogleApiSourcesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListGoogleApiSourcesPager: + r"""List GoogleApiSources. + + .. 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 eventarc_v1 + + def sample_list_google_api_sources(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListGoogleApiSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_api_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest, dict]): + The request object. The request message for the + ListGoogleApiSources method. + parent (str): + Required. The parent collection to + list GoogleApiSources on. + + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesPager: + The response message for the ListGoogleApiSources + method. + + 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. + has_flattened_params = any([parent]) + 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, eventarc.ListGoogleApiSourcesRequest): + request = eventarc.ListGoogleApiSourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_google_api_sources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListGoogleApiSourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_google_api_source( + self, + request: Optional[Union[eventarc.CreateGoogleApiSourceRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + google_api_source_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create a new GoogleApiSource in a particular project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import eventarc_v1 + + def sample_create_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source=google_api_source, + google_api_source_id="google_api_source_id_value", + ) + + # Make the request + operation = client.create_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest, dict]): + The request object. The request message for the + CreateGoogleApiSource method. + parent (str): + Required. The parent collection in + which to add this google api source. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): + Required. The google api source to + create. + + This corresponds to the ``google_api_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_api_source_id (str): + Required. The user-provided ID to be assigned to the + GoogleApiSource. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + + This corresponds to the ``google_api_source_id`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # 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. + has_flattened_params = any([parent, google_api_source, google_api_source_id]) + 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, eventarc.CreateGoogleApiSourceRequest): + request = eventarc.CreateGoogleApiSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if google_api_source is not None: + request.google_api_source = google_api_source + if google_api_source_id is not None: + request.google_api_source_id = google_api_source_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_google_api_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gce_google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_google_api_source( + self, + request: Optional[Union[eventarc.UpdateGoogleApiSourceRequest, dict]] = None, + *, + google_api_source: Optional[gce_google_api_source.GoogleApiSource] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update a single GoogleApiSource. + + .. 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 eventarc_v1 + + def sample_update_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.UpdateGoogleApiSourceRequest( + google_api_source=google_api_source, + ) + + # Make the request + operation = client.update_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest, dict]): + The request object. The request message for the + UpdateGoogleApiSource method. + google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): + Required. The GoogleApiSource to be + updated. + + This corresponds to the ``google_api_source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields + explicitly provided are updated. If no field mask is + provided, all provided fields in the request are + updated. To update all fields, provide a field mask of + "*". + + This corresponds to the ``update_mask`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # 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. + has_flattened_params = any([google_api_source, update_mask]) + 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, eventarc.UpdateGoogleApiSourceRequest): + request = eventarc.UpdateGoogleApiSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_api_source is not None: + request.google_api_source = google_api_source + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_google_api_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("google_api_source.name", request.google_api_source.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gce_google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_google_api_source( + self, + request: Optional[Union[eventarc.DeleteGoogleApiSourceRequest, dict]] = None, + *, + name: Optional[str] = None, + etag: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete a single GoogleApiSource. + + .. 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 eventarc_v1 + + def sample_delete_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest, dict]): + The request object. The request message for the + DeleteGoogleApiSource method. + name (str): + Required. The name of the + GoogleApiSource to be deleted. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + etag (str): + Optional. If provided, the MessageBus + will only be deleted if the etag matches + the current etag on the resource. + + This corresponds to the ``etag`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.eventarc_v1.types.GoogleApiSource` + A GoogleApiSource represents a subscription of 1P events + from a MessageBus. + + """ + # 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. + has_flattened_params = any([name, etag]) + 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, eventarc.DeleteGoogleApiSourceRequest): + request = eventarc.DeleteGoogleApiSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if etag is not None: + request.etag = etag + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_google_api_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + google_api_source.GoogleApiSource, + metadata_type=eventarc.OperationMetadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "EventarcClient": return self diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/pagers.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/pagers.py index c3b945abe9b1..db8ae4b7dfec 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/pagers.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/pagers.py @@ -42,7 +42,11 @@ channel, channel_connection, discovery, + enrollment, eventarc, + google_api_source, + message_bus, + pipeline, trigger, ) @@ -653,3 +657,763 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMessageBusesPager: + """A pager for iterating through ``list_message_buses`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``message_buses`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMessageBuses`` requests and continue to iterate + through the ``message_buses`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` + 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[..., eventarc.ListMessageBusesResponse], + request: eventarc.ListMessageBusesRequest, + response: eventarc.ListMessageBusesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListMessageBusesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListMessageBusesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListMessageBusesRequest(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[eventarc.ListMessageBusesResponse]: + 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[message_bus.MessageBus]: + for page in self.pages: + yield from page.message_buses + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMessageBusesAsyncPager: + """A pager for iterating through ``list_message_buses`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``message_buses`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMessageBuses`` requests and continue to iterate + through the ``message_buses`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[eventarc.ListMessageBusesResponse]], + request: eventarc.ListMessageBusesRequest, + response: eventarc.ListMessageBusesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListMessageBusesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListMessageBusesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListMessageBusesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[eventarc.ListMessageBusesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[message_bus.MessageBus]: + async def async_generator(): + async for page in self.pages: + for response in page.message_buses: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMessageBusEnrollmentsPager: + """A pager for iterating through ``list_message_bus_enrollments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``enrollments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMessageBusEnrollments`` requests and continue to iterate + through the ``enrollments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` + 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[..., eventarc.ListMessageBusEnrollmentsResponse], + request: eventarc.ListMessageBusEnrollmentsRequest, + response: eventarc.ListMessageBusEnrollmentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListMessageBusEnrollmentsRequest(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[eventarc.ListMessageBusEnrollmentsResponse]: + 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[str]: + for page in self.pages: + yield from page.enrollments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMessageBusEnrollmentsAsyncPager: + """A pager for iterating through ``list_message_bus_enrollments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``enrollments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMessageBusEnrollments`` requests and continue to iterate + through the ``enrollments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[eventarc.ListMessageBusEnrollmentsResponse]], + request: eventarc.ListMessageBusEnrollmentsRequest, + response: eventarc.ListMessageBusEnrollmentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListMessageBusEnrollmentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[eventarc.ListMessageBusEnrollmentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[str]: + async def async_generator(): + async for page in self.pages: + for response in page.enrollments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEnrollmentsPager: + """A pager for iterating through ``list_enrollments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``enrollments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEnrollments`` requests and continue to iterate + through the ``enrollments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` + 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[..., eventarc.ListEnrollmentsResponse], + request: eventarc.ListEnrollmentsRequest, + response: eventarc.ListEnrollmentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListEnrollmentsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListEnrollmentsResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListEnrollmentsRequest(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[eventarc.ListEnrollmentsResponse]: + 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[enrollment.Enrollment]: + for page in self.pages: + yield from page.enrollments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEnrollmentsAsyncPager: + """A pager for iterating through ``list_enrollments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``enrollments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEnrollments`` requests and continue to iterate + through the ``enrollments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListEnrollmentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[eventarc.ListEnrollmentsResponse]], + request: eventarc.ListEnrollmentsRequest, + response: eventarc.ListEnrollmentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListEnrollmentsRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListEnrollmentsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListEnrollmentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[eventarc.ListEnrollmentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[enrollment.Enrollment]: + async def async_generator(): + async for page in self.pages: + for response in page.enrollments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPipelinesPager: + """A pager for iterating through ``list_pipelines`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``pipelines`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPipelines`` requests and continue to iterate + through the ``pipelines`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` + 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[..., eventarc.ListPipelinesResponse], + request: eventarc.ListPipelinesRequest, + response: eventarc.ListPipelinesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListPipelinesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListPipelinesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListPipelinesRequest(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[eventarc.ListPipelinesResponse]: + 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[pipeline.Pipeline]: + for page in self.pages: + yield from page.pipelines + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPipelinesAsyncPager: + """A pager for iterating through ``list_pipelines`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``pipelines`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPipelines`` requests and continue to iterate + through the ``pipelines`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListPipelinesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[eventarc.ListPipelinesResponse]], + request: eventarc.ListPipelinesRequest, + response: eventarc.ListPipelinesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListPipelinesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListPipelinesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListPipelinesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[eventarc.ListPipelinesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[pipeline.Pipeline]: + async def async_generator(): + async for page in self.pages: + for response in page.pipelines: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGoogleApiSourcesPager: + """A pager for iterating through ``list_google_api_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``google_api_sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGoogleApiSources`` requests and continue to iterate + through the ``google_api_sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` + 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[..., eventarc.ListGoogleApiSourcesResponse], + request: eventarc.ListGoogleApiSourcesRequest, + response: eventarc.ListGoogleApiSourcesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListGoogleApiSourcesRequest(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[eventarc.ListGoogleApiSourcesResponse]: + 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[google_api_source.GoogleApiSource]: + for page in self.pages: + yield from page.google_api_sources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGoogleApiSourcesAsyncPager: + """A pager for iterating through ``list_google_api_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``google_api_sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGoogleApiSources`` requests and continue to iterate + through the ``google_api_sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[eventarc.ListGoogleApiSourcesResponse]], + request: eventarc.ListGoogleApiSourcesRequest, + response: eventarc.ListGoogleApiSourcesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest): + The initial request object. + response (google.cloud.eventarc_v1.types.ListGoogleApiSourcesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = eventarc.ListGoogleApiSourcesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[eventarc.ListGoogleApiSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[google_api_source.GoogleApiSource]: + async def async_generator(): + async for page in self.pages: + for response in page.google_api_sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py index cfc6a4959886..f19e367869c3 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -33,13 +33,15 @@ channel, channel_connection, discovery, + enrollment, eventarc, + google_api_source, ) from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import trigger +from google.cloud.eventarc_v1.types import message_bus, pipeline, trigger DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -144,92 +146,377 @@ def _prep_wrapped_messages(self, client_info): self._wrapped_methods = { self.get_trigger: gapic_v1.method.wrap_method( self.get_trigger, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_triggers: gapic_v1.method.wrap_method( self.list_triggers, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.create_trigger: gapic_v1.method.wrap_method( self.create_trigger, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.update_trigger: gapic_v1.method.wrap_method( self.update_trigger, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_trigger: gapic_v1.method.wrap_method( self.delete_trigger, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_channel: gapic_v1.method.wrap_method( self.get_channel, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_channels: gapic_v1.method.wrap_method( self.list_channels, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.create_channel_: gapic_v1.method.wrap_method( self.create_channel_, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.update_channel: gapic_v1.method.wrap_method( self.update_channel, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_channel: gapic_v1.method.wrap_method( self.delete_channel, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_provider: gapic_v1.method.wrap_method( self.get_provider, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_providers: gapic_v1.method.wrap_method( self.list_providers, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_channel_connection: gapic_v1.method.wrap_method( self.get_channel_connection, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_channel_connections: gapic_v1.method.wrap_method( self.list_channel_connections, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.create_channel_connection: gapic_v1.method.wrap_method( self.create_channel_connection, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_channel_connection: gapic_v1.method.wrap_method( self.delete_channel_connection, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_google_channel_config: gapic_v1.method.wrap_method( self.get_google_channel_config, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.update_google_channel_config: gapic_v1.method.wrap_method( self.update_google_channel_config, - default_timeout=None, + default_timeout=60.0, + client_info=client_info, + ), + self.get_message_bus: gapic_v1.method.wrap_method( + self.get_message_bus, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_message_buses: gapic_v1.method.wrap_method( + self.list_message_buses, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_message_bus_enrollments: gapic_v1.method.wrap_method( + self.list_message_bus_enrollments, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_message_bus: gapic_v1.method.wrap_method( + self.create_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.update_message_bus: gapic_v1.method.wrap_method( + self.update_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_message_bus: gapic_v1.method.wrap_method( + self.delete_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.get_enrollment: gapic_v1.method.wrap_method( + self.get_enrollment, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_enrollments: gapic_v1.method.wrap_method( + self.list_enrollments, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_enrollment: gapic_v1.method.wrap_method( + self.create_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.update_enrollment: gapic_v1.method.wrap_method( + self.update_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_enrollment: gapic_v1.method.wrap_method( + self.delete_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.get_pipeline: gapic_v1.method.wrap_method( + self.get_pipeline, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_pipelines: gapic_v1.method.wrap_method( + self.list_pipelines, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_pipeline: gapic_v1.method.wrap_method( + self.create_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.update_pipeline: gapic_v1.method.wrap_method( + self.update_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_pipeline: gapic_v1.method.wrap_method( + self.delete_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.get_google_api_source: gapic_v1.method.wrap_method( + self.get_google_api_source, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_google_api_sources: gapic_v1.method.wrap_method( + self.list_google_api_sources, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_google_api_source: gapic_v1.method.wrap_method( + self.create_google_api_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_google_api_source: gapic_v1.method.wrap_method( + self.update_google_api_source, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_google_api_source: gapic_v1.method.wrap_method( + self.delete_google_api_source, + default_timeout=60.0, client_info=client_info, ), self.get_location: gapic_v1.method.wrap_method( @@ -467,6 +754,212 @@ def update_google_channel_config( ]: raise NotImplementedError() + @property + def get_message_bus( + self, + ) -> Callable[ + [eventarc.GetMessageBusRequest], + Union[message_bus.MessageBus, Awaitable[message_bus.MessageBus]], + ]: + raise NotImplementedError() + + @property + def list_message_buses( + self, + ) -> Callable[ + [eventarc.ListMessageBusesRequest], + Union[ + eventarc.ListMessageBusesResponse, + Awaitable[eventarc.ListMessageBusesResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_message_bus_enrollments( + self, + ) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + Union[ + eventarc.ListMessageBusEnrollmentsResponse, + Awaitable[eventarc.ListMessageBusEnrollmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_message_bus( + self, + ) -> Callable[ + [eventarc.CreateMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_message_bus( + self, + ) -> Callable[ + [eventarc.UpdateMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_message_bus( + self, + ) -> Callable[ + [eventarc.DeleteMessageBusRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_enrollment( + self, + ) -> Callable[ + [eventarc.GetEnrollmentRequest], + Union[enrollment.Enrollment, Awaitable[enrollment.Enrollment]], + ]: + raise NotImplementedError() + + @property + def list_enrollments( + self, + ) -> Callable[ + [eventarc.ListEnrollmentsRequest], + Union[ + eventarc.ListEnrollmentsResponse, + Awaitable[eventarc.ListEnrollmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_enrollment( + self, + ) -> Callable[ + [eventarc.CreateEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_enrollment( + self, + ) -> Callable[ + [eventarc.UpdateEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_enrollment( + self, + ) -> Callable[ + [eventarc.DeleteEnrollmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_pipeline( + self, + ) -> Callable[ + [eventarc.GetPipelineRequest], + Union[pipeline.Pipeline, Awaitable[pipeline.Pipeline]], + ]: + raise NotImplementedError() + + @property + def list_pipelines( + self, + ) -> Callable[ + [eventarc.ListPipelinesRequest], + Union[ + eventarc.ListPipelinesResponse, Awaitable[eventarc.ListPipelinesResponse] + ], + ]: + raise NotImplementedError() + + @property + def create_pipeline( + self, + ) -> Callable[ + [eventarc.CreatePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_pipeline( + self, + ) -> Callable[ + [eventarc.UpdatePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_pipeline( + self, + ) -> Callable[ + [eventarc.DeletePipelineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_google_api_source( + self, + ) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + Union[ + google_api_source.GoogleApiSource, + Awaitable[google_api_source.GoogleApiSource], + ], + ]: + raise NotImplementedError() + + @property + def list_google_api_sources( + self, + ) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + Union[ + eventarc.ListGoogleApiSourcesResponse, + Awaitable[eventarc.ListGoogleApiSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_google_api_source( + self, + ) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_google_api_source( + self, + ) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_google_api_source( + self, + ) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py index 8db9512d6286..9f37c908a47d 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc.py @@ -30,13 +30,15 @@ channel, channel_connection, discovery, + enrollment, eventarc, + google_api_source, ) from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import trigger +from google.cloud.eventarc_v1.types import message_bus, pipeline, trigger from .base import DEFAULT_CLIENT_INFO, EventarcTransport @@ -743,6 +745,565 @@ def update_google_channel_config( ) return self._stubs["update_google_channel_config"] + @property + def get_message_bus( + self, + ) -> Callable[[eventarc.GetMessageBusRequest], message_bus.MessageBus]: + r"""Return a callable for the get message bus method over gRPC. + + Get a single MessageBus. + + Returns: + Callable[[~.GetMessageBusRequest], + ~.MessageBus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_message_bus" not in self._stubs: + self._stubs["get_message_bus"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetMessageBus", + request_serializer=eventarc.GetMessageBusRequest.serialize, + response_deserializer=message_bus.MessageBus.deserialize, + ) + return self._stubs["get_message_bus"] + + @property + def list_message_buses( + self, + ) -> Callable[ + [eventarc.ListMessageBusesRequest], eventarc.ListMessageBusesResponse + ]: + r"""Return a callable for the list message buses method over gRPC. + + List message buses. + + Returns: + Callable[[~.ListMessageBusesRequest], + ~.ListMessageBusesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_message_buses" not in self._stubs: + self._stubs["list_message_buses"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListMessageBuses", + request_serializer=eventarc.ListMessageBusesRequest.serialize, + response_deserializer=eventarc.ListMessageBusesResponse.deserialize, + ) + return self._stubs["list_message_buses"] + + @property + def list_message_bus_enrollments( + self, + ) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + eventarc.ListMessageBusEnrollmentsResponse, + ]: + r"""Return a callable for the list message bus enrollments method over gRPC. + + List message bus enrollments. + + Returns: + Callable[[~.ListMessageBusEnrollmentsRequest], + ~.ListMessageBusEnrollmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_message_bus_enrollments" not in self._stubs: + self._stubs["list_message_bus_enrollments"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments", + request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, + ) + return self._stubs["list_message_bus_enrollments"] + + @property + def create_message_bus( + self, + ) -> Callable[[eventarc.CreateMessageBusRequest], operations_pb2.Operation]: + r"""Return a callable for the create message bus method over gRPC. + + Create a new MessageBus in a particular project and + location. + + Returns: + Callable[[~.CreateMessageBusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_message_bus" not in self._stubs: + self._stubs["create_message_bus"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateMessageBus", + request_serializer=eventarc.CreateMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_message_bus"] + + @property + def update_message_bus( + self, + ) -> Callable[[eventarc.UpdateMessageBusRequest], operations_pb2.Operation]: + r"""Return a callable for the update message bus method over gRPC. + + Update a single message bus. + + Returns: + Callable[[~.UpdateMessageBusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_message_bus" not in self._stubs: + self._stubs["update_message_bus"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus", + request_serializer=eventarc.UpdateMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_message_bus"] + + @property + def delete_message_bus( + self, + ) -> Callable[[eventarc.DeleteMessageBusRequest], operations_pb2.Operation]: + r"""Return a callable for the delete message bus method over gRPC. + + Delete a single message bus. + + Returns: + Callable[[~.DeleteMessageBusRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_message_bus" not in self._stubs: + self._stubs["delete_message_bus"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus", + request_serializer=eventarc.DeleteMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_message_bus"] + + @property + def get_enrollment( + self, + ) -> Callable[[eventarc.GetEnrollmentRequest], enrollment.Enrollment]: + r"""Return a callable for the get enrollment method over gRPC. + + Get a single Enrollment. + + Returns: + Callable[[~.GetEnrollmentRequest], + ~.Enrollment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_enrollment" not in self._stubs: + self._stubs["get_enrollment"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetEnrollment", + request_serializer=eventarc.GetEnrollmentRequest.serialize, + response_deserializer=enrollment.Enrollment.deserialize, + ) + return self._stubs["get_enrollment"] + + @property + def list_enrollments( + self, + ) -> Callable[[eventarc.ListEnrollmentsRequest], eventarc.ListEnrollmentsResponse]: + r"""Return a callable for the list enrollments method over gRPC. + + List Enrollments. + + Returns: + Callable[[~.ListEnrollmentsRequest], + ~.ListEnrollmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_enrollments" not in self._stubs: + self._stubs["list_enrollments"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListEnrollments", + request_serializer=eventarc.ListEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListEnrollmentsResponse.deserialize, + ) + return self._stubs["list_enrollments"] + + @property + def create_enrollment( + self, + ) -> Callable[[eventarc.CreateEnrollmentRequest], operations_pb2.Operation]: + r"""Return a callable for the create enrollment method over gRPC. + + Create a new Enrollment in a particular project and + location. + + Returns: + Callable[[~.CreateEnrollmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_enrollment" not in self._stubs: + self._stubs["create_enrollment"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateEnrollment", + request_serializer=eventarc.CreateEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_enrollment"] + + @property + def update_enrollment( + self, + ) -> Callable[[eventarc.UpdateEnrollmentRequest], operations_pb2.Operation]: + r"""Return a callable for the update enrollment method over gRPC. + + Update a single Enrollment. + + Returns: + Callable[[~.UpdateEnrollmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_enrollment" not in self._stubs: + self._stubs["update_enrollment"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment", + request_serializer=eventarc.UpdateEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_enrollment"] + + @property + def delete_enrollment( + self, + ) -> Callable[[eventarc.DeleteEnrollmentRequest], operations_pb2.Operation]: + r"""Return a callable for the delete enrollment method over gRPC. + + Delete a single Enrollment. + + Returns: + Callable[[~.DeleteEnrollmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_enrollment" not in self._stubs: + self._stubs["delete_enrollment"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment", + request_serializer=eventarc.DeleteEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_enrollment"] + + @property + def get_pipeline( + self, + ) -> Callable[[eventarc.GetPipelineRequest], pipeline.Pipeline]: + r"""Return a callable for the get pipeline method over gRPC. + + Get a single Pipeline. + + Returns: + Callable[[~.GetPipelineRequest], + ~.Pipeline]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_pipeline" not in self._stubs: + self._stubs["get_pipeline"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetPipeline", + request_serializer=eventarc.GetPipelineRequest.serialize, + response_deserializer=pipeline.Pipeline.deserialize, + ) + return self._stubs["get_pipeline"] + + @property + def list_pipelines( + self, + ) -> Callable[[eventarc.ListPipelinesRequest], eventarc.ListPipelinesResponse]: + r"""Return a callable for the list pipelines method over gRPC. + + List pipelines. + + Returns: + Callable[[~.ListPipelinesRequest], + ~.ListPipelinesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_pipelines" not in self._stubs: + self._stubs["list_pipelines"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListPipelines", + request_serializer=eventarc.ListPipelinesRequest.serialize, + response_deserializer=eventarc.ListPipelinesResponse.deserialize, + ) + return self._stubs["list_pipelines"] + + @property + def create_pipeline( + self, + ) -> Callable[[eventarc.CreatePipelineRequest], operations_pb2.Operation]: + r"""Return a callable for the create pipeline method over gRPC. + + Create a new Pipeline in a particular project and + location. + + Returns: + Callable[[~.CreatePipelineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_pipeline" not in self._stubs: + self._stubs["create_pipeline"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreatePipeline", + request_serializer=eventarc.CreatePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_pipeline"] + + @property + def update_pipeline( + self, + ) -> Callable[[eventarc.UpdatePipelineRequest], operations_pb2.Operation]: + r"""Return a callable for the update pipeline method over gRPC. + + Update a single pipeline. + + Returns: + Callable[[~.UpdatePipelineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_pipeline" not in self._stubs: + self._stubs["update_pipeline"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdatePipeline", + request_serializer=eventarc.UpdatePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_pipeline"] + + @property + def delete_pipeline( + self, + ) -> Callable[[eventarc.DeletePipelineRequest], operations_pb2.Operation]: + r"""Return a callable for the delete pipeline method over gRPC. + + Delete a single pipeline. + + Returns: + Callable[[~.DeletePipelineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_pipeline" not in self._stubs: + self._stubs["delete_pipeline"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeletePipeline", + request_serializer=eventarc.DeletePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_pipeline"] + + @property + def get_google_api_source( + self, + ) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], google_api_source.GoogleApiSource + ]: + r"""Return a callable for the get google api source method over gRPC. + + Get a single GoogleApiSource. + + Returns: + Callable[[~.GetGoogleApiSourceRequest], + ~.GoogleApiSource]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_google_api_source" not in self._stubs: + self._stubs["get_google_api_source"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource", + request_serializer=eventarc.GetGoogleApiSourceRequest.serialize, + response_deserializer=google_api_source.GoogleApiSource.deserialize, + ) + return self._stubs["get_google_api_source"] + + @property + def list_google_api_sources( + self, + ) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], eventarc.ListGoogleApiSourcesResponse + ]: + r"""Return a callable for the list google api sources method over gRPC. + + List GoogleApiSources. + + Returns: + Callable[[~.ListGoogleApiSourcesRequest], + ~.ListGoogleApiSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_google_api_sources" not in self._stubs: + self._stubs["list_google_api_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources", + request_serializer=eventarc.ListGoogleApiSourcesRequest.serialize, + response_deserializer=eventarc.ListGoogleApiSourcesResponse.deserialize, + ) + return self._stubs["list_google_api_sources"] + + @property + def create_google_api_source( + self, + ) -> Callable[[eventarc.CreateGoogleApiSourceRequest], operations_pb2.Operation]: + r"""Return a callable for the create google api source method over gRPC. + + Create a new GoogleApiSource in a particular project + and location. + + Returns: + Callable[[~.CreateGoogleApiSourceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_google_api_source" not in self._stubs: + self._stubs["create_google_api_source"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource", + request_serializer=eventarc.CreateGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_google_api_source"] + + @property + def update_google_api_source( + self, + ) -> Callable[[eventarc.UpdateGoogleApiSourceRequest], operations_pb2.Operation]: + r"""Return a callable for the update google api source method over gRPC. + + Update a single GoogleApiSource. + + Returns: + Callable[[~.UpdateGoogleApiSourceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_google_api_source" not in self._stubs: + self._stubs["update_google_api_source"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource", + request_serializer=eventarc.UpdateGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_google_api_source"] + + @property + def delete_google_api_source( + self, + ) -> Callable[[eventarc.DeleteGoogleApiSourceRequest], operations_pb2.Operation]: + r"""Return a callable for the delete google api source method over gRPC. + + Delete a single GoogleApiSource. + + Returns: + Callable[[~.DeleteGoogleApiSourceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_google_api_source" not in self._stubs: + self._stubs["delete_google_api_source"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource", + request_serializer=eventarc.DeleteGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_google_api_source"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py index 593bed7a83cc..1394764fde8c 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/grpc_asyncio.py @@ -33,13 +33,15 @@ channel, channel_connection, discovery, + enrollment, eventarc, + google_api_source, ) from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import trigger +from google.cloud.eventarc_v1.types import message_bus, pipeline, trigger from .base import DEFAULT_CLIENT_INFO, EventarcTransport from .grpc import EventarcGrpcTransport @@ -768,97 +770,971 @@ def update_google_channel_config( ) return self._stubs["update_google_channel_config"] + @property + def get_message_bus( + self, + ) -> Callable[[eventarc.GetMessageBusRequest], Awaitable[message_bus.MessageBus]]: + r"""Return a callable for the get message bus method over gRPC. + + Get a single MessageBus. + + Returns: + Callable[[~.GetMessageBusRequest], + Awaitable[~.MessageBus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_message_bus" not in self._stubs: + self._stubs["get_message_bus"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetMessageBus", + request_serializer=eventarc.GetMessageBusRequest.serialize, + response_deserializer=message_bus.MessageBus.deserialize, + ) + return self._stubs["get_message_bus"] + + @property + def list_message_buses( + self, + ) -> Callable[ + [eventarc.ListMessageBusesRequest], Awaitable[eventarc.ListMessageBusesResponse] + ]: + r"""Return a callable for the list message buses method over gRPC. + + List message buses. + + Returns: + Callable[[~.ListMessageBusesRequest], + Awaitable[~.ListMessageBusesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_message_buses" not in self._stubs: + self._stubs["list_message_buses"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListMessageBuses", + request_serializer=eventarc.ListMessageBusesRequest.serialize, + response_deserializer=eventarc.ListMessageBusesResponse.deserialize, + ) + return self._stubs["list_message_buses"] + + @property + def list_message_bus_enrollments( + self, + ) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + Awaitable[eventarc.ListMessageBusEnrollmentsResponse], + ]: + r"""Return a callable for the list message bus enrollments method over gRPC. + + List message bus enrollments. + + Returns: + Callable[[~.ListMessageBusEnrollmentsRequest], + Awaitable[~.ListMessageBusEnrollmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_message_bus_enrollments" not in self._stubs: + self._stubs["list_message_bus_enrollments"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListMessageBusEnrollments", + request_serializer=eventarc.ListMessageBusEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListMessageBusEnrollmentsResponse.deserialize, + ) + return self._stubs["list_message_bus_enrollments"] + + @property + def create_message_bus( + self, + ) -> Callable[ + [eventarc.CreateMessageBusRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create message bus method over gRPC. + + Create a new MessageBus in a particular project and + location. + + Returns: + Callable[[~.CreateMessageBusRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_message_bus" not in self._stubs: + self._stubs["create_message_bus"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateMessageBus", + request_serializer=eventarc.CreateMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_message_bus"] + + @property + def update_message_bus( + self, + ) -> Callable[ + [eventarc.UpdateMessageBusRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update message bus method over gRPC. + + Update a single message bus. + + Returns: + Callable[[~.UpdateMessageBusRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_message_bus" not in self._stubs: + self._stubs["update_message_bus"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateMessageBus", + request_serializer=eventarc.UpdateMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_message_bus"] + + @property + def delete_message_bus( + self, + ) -> Callable[ + [eventarc.DeleteMessageBusRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete message bus method over gRPC. + + Delete a single message bus. + + Returns: + Callable[[~.DeleteMessageBusRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_message_bus" not in self._stubs: + self._stubs["delete_message_bus"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteMessageBus", + request_serializer=eventarc.DeleteMessageBusRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_message_bus"] + + @property + def get_enrollment( + self, + ) -> Callable[[eventarc.GetEnrollmentRequest], Awaitable[enrollment.Enrollment]]: + r"""Return a callable for the get enrollment method over gRPC. + + Get a single Enrollment. + + Returns: + Callable[[~.GetEnrollmentRequest], + Awaitable[~.Enrollment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_enrollment" not in self._stubs: + self._stubs["get_enrollment"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetEnrollment", + request_serializer=eventarc.GetEnrollmentRequest.serialize, + response_deserializer=enrollment.Enrollment.deserialize, + ) + return self._stubs["get_enrollment"] + + @property + def list_enrollments( + self, + ) -> Callable[ + [eventarc.ListEnrollmentsRequest], Awaitable[eventarc.ListEnrollmentsResponse] + ]: + r"""Return a callable for the list enrollments method over gRPC. + + List Enrollments. + + Returns: + Callable[[~.ListEnrollmentsRequest], + Awaitable[~.ListEnrollmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_enrollments" not in self._stubs: + self._stubs["list_enrollments"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListEnrollments", + request_serializer=eventarc.ListEnrollmentsRequest.serialize, + response_deserializer=eventarc.ListEnrollmentsResponse.deserialize, + ) + return self._stubs["list_enrollments"] + + @property + def create_enrollment( + self, + ) -> Callable[ + [eventarc.CreateEnrollmentRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create enrollment method over gRPC. + + Create a new Enrollment in a particular project and + location. + + Returns: + Callable[[~.CreateEnrollmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_enrollment" not in self._stubs: + self._stubs["create_enrollment"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateEnrollment", + request_serializer=eventarc.CreateEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_enrollment"] + + @property + def update_enrollment( + self, + ) -> Callable[ + [eventarc.UpdateEnrollmentRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update enrollment method over gRPC. + + Update a single Enrollment. + + Returns: + Callable[[~.UpdateEnrollmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_enrollment" not in self._stubs: + self._stubs["update_enrollment"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateEnrollment", + request_serializer=eventarc.UpdateEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_enrollment"] + + @property + def delete_enrollment( + self, + ) -> Callable[ + [eventarc.DeleteEnrollmentRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete enrollment method over gRPC. + + Delete a single Enrollment. + + Returns: + Callable[[~.DeleteEnrollmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_enrollment" not in self._stubs: + self._stubs["delete_enrollment"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteEnrollment", + request_serializer=eventarc.DeleteEnrollmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_enrollment"] + + @property + def get_pipeline( + self, + ) -> Callable[[eventarc.GetPipelineRequest], Awaitable[pipeline.Pipeline]]: + r"""Return a callable for the get pipeline method over gRPC. + + Get a single Pipeline. + + Returns: + Callable[[~.GetPipelineRequest], + Awaitable[~.Pipeline]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_pipeline" not in self._stubs: + self._stubs["get_pipeline"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetPipeline", + request_serializer=eventarc.GetPipelineRequest.serialize, + response_deserializer=pipeline.Pipeline.deserialize, + ) + return self._stubs["get_pipeline"] + + @property + def list_pipelines( + self, + ) -> Callable[ + [eventarc.ListPipelinesRequest], Awaitable[eventarc.ListPipelinesResponse] + ]: + r"""Return a callable for the list pipelines method over gRPC. + + List pipelines. + + Returns: + Callable[[~.ListPipelinesRequest], + Awaitable[~.ListPipelinesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_pipelines" not in self._stubs: + self._stubs["list_pipelines"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListPipelines", + request_serializer=eventarc.ListPipelinesRequest.serialize, + response_deserializer=eventarc.ListPipelinesResponse.deserialize, + ) + return self._stubs["list_pipelines"] + + @property + def create_pipeline( + self, + ) -> Callable[ + [eventarc.CreatePipelineRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create pipeline method over gRPC. + + Create a new Pipeline in a particular project and + location. + + Returns: + Callable[[~.CreatePipelineRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_pipeline" not in self._stubs: + self._stubs["create_pipeline"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreatePipeline", + request_serializer=eventarc.CreatePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_pipeline"] + + @property + def update_pipeline( + self, + ) -> Callable[ + [eventarc.UpdatePipelineRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update pipeline method over gRPC. + + Update a single pipeline. + + Returns: + Callable[[~.UpdatePipelineRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_pipeline" not in self._stubs: + self._stubs["update_pipeline"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdatePipeline", + request_serializer=eventarc.UpdatePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_pipeline"] + + @property + def delete_pipeline( + self, + ) -> Callable[ + [eventarc.DeletePipelineRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete pipeline method over gRPC. + + Delete a single pipeline. + + Returns: + Callable[[~.DeletePipelineRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_pipeline" not in self._stubs: + self._stubs["delete_pipeline"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeletePipeline", + request_serializer=eventarc.DeletePipelineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_pipeline"] + + @property + def get_google_api_source( + self, + ) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], + Awaitable[google_api_source.GoogleApiSource], + ]: + r"""Return a callable for the get google api source method over gRPC. + + Get a single GoogleApiSource. + + Returns: + Callable[[~.GetGoogleApiSourceRequest], + Awaitable[~.GoogleApiSource]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_google_api_source" not in self._stubs: + self._stubs["get_google_api_source"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/GetGoogleApiSource", + request_serializer=eventarc.GetGoogleApiSourceRequest.serialize, + response_deserializer=google_api_source.GoogleApiSource.deserialize, + ) + return self._stubs["get_google_api_source"] + + @property + def list_google_api_sources( + self, + ) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], + Awaitable[eventarc.ListGoogleApiSourcesResponse], + ]: + r"""Return a callable for the list google api sources method over gRPC. + + List GoogleApiSources. + + Returns: + Callable[[~.ListGoogleApiSourcesRequest], + Awaitable[~.ListGoogleApiSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_google_api_sources" not in self._stubs: + self._stubs["list_google_api_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/ListGoogleApiSources", + request_serializer=eventarc.ListGoogleApiSourcesRequest.serialize, + response_deserializer=eventarc.ListGoogleApiSourcesResponse.deserialize, + ) + return self._stubs["list_google_api_sources"] + + @property + def create_google_api_source( + self, + ) -> Callable[ + [eventarc.CreateGoogleApiSourceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create google api source method over gRPC. + + Create a new GoogleApiSource in a particular project + and location. + + Returns: + Callable[[~.CreateGoogleApiSourceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_google_api_source" not in self._stubs: + self._stubs["create_google_api_source"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/CreateGoogleApiSource", + request_serializer=eventarc.CreateGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_google_api_source"] + + @property + def update_google_api_source( + self, + ) -> Callable[ + [eventarc.UpdateGoogleApiSourceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update google api source method over gRPC. + + Update a single GoogleApiSource. + + Returns: + Callable[[~.UpdateGoogleApiSourceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_google_api_source" not in self._stubs: + self._stubs["update_google_api_source"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/UpdateGoogleApiSource", + request_serializer=eventarc.UpdateGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_google_api_source"] + + @property + def delete_google_api_source( + self, + ) -> Callable[ + [eventarc.DeleteGoogleApiSourceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete google api source method over gRPC. + + Delete a single GoogleApiSource. + + Returns: + Callable[[~.DeleteGoogleApiSourceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_google_api_source" not in self._stubs: + self._stubs["delete_google_api_source"] = self.grpc_channel.unary_unary( + "/google.cloud.eventarc.v1.Eventarc/DeleteGoogleApiSource", + request_serializer=eventarc.DeleteGoogleApiSourceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_google_api_source"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.get_trigger: self._wrap_method( self.get_trigger, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_triggers: self._wrap_method( self.list_triggers, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.create_trigger: self._wrap_method( self.create_trigger, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.update_trigger: self._wrap_method( self.update_trigger, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_trigger: self._wrap_method( self.delete_trigger, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_channel: self._wrap_method( self.get_channel, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_channels: self._wrap_method( self.list_channels, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.create_channel_: self._wrap_method( self.create_channel_, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.update_channel: self._wrap_method( self.update_channel, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_channel: self._wrap_method( self.delete_channel, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_provider: self._wrap_method( self.get_provider, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_providers: self._wrap_method( self.list_providers, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_channel_connection: self._wrap_method( self.get_channel_connection, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_channel_connections: self._wrap_method( self.list_channel_connections, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.create_channel_connection: self._wrap_method( self.create_channel_connection, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_channel_connection: self._wrap_method( self.delete_channel_connection, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_google_channel_config: self._wrap_method( self.get_google_channel_config, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.update_google_channel_config: self._wrap_method( self.update_google_channel_config, - default_timeout=None, + default_timeout=60.0, + client_info=client_info, + ), + self.get_message_bus: self._wrap_method( + self.get_message_bus, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_message_buses: self._wrap_method( + self.list_message_buses, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_message_bus_enrollments: self._wrap_method( + self.list_message_bus_enrollments, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_message_bus: self._wrap_method( + self.create_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.update_message_bus: self._wrap_method( + self.update_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_message_bus: self._wrap_method( + self.delete_message_bus, + default_timeout=60.0, + client_info=client_info, + ), + self.get_enrollment: self._wrap_method( + self.get_enrollment, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_enrollments: self._wrap_method( + self.list_enrollments, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_enrollment: self._wrap_method( + self.create_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.update_enrollment: self._wrap_method( + self.update_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_enrollment: self._wrap_method( + self.delete_enrollment, + default_timeout=60.0, + client_info=client_info, + ), + self.get_pipeline: self._wrap_method( + self.get_pipeline, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_pipelines: self._wrap_method( + self.list_pipelines, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_pipeline: self._wrap_method( + self.create_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.update_pipeline: self._wrap_method( + self.update_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_pipeline: self._wrap_method( + self.delete_pipeline, + default_timeout=60.0, + client_info=client_info, + ), + self.get_google_api_source: self._wrap_method( + self.get_google_api_source, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_google_api_sources: self._wrap_method( + self.list_google_api_sources, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_google_api_source: self._wrap_method( + self.create_google_api_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_google_api_source: self._wrap_method( + self.update_google_api_source, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_google_api_source: self._wrap_method( + self.delete_google_api_source, + default_timeout=60.0, client_info=client_info, ), self.get_location: self._wrap_method( diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py index 97082866535e..936d6af4722e 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest.py @@ -35,13 +35,15 @@ channel, channel_connection, discovery, + enrollment, eventarc, + google_api_source, ) from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import trigger +from google.cloud.eventarc_v1.types import message_bus, pipeline, trigger from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseEventarcRestTransport @@ -90,6 +92,38 @@ def post_create_channel_connection(self, response): logging.log(f"Received response: {response}") return response + def pre_create_enrollment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_enrollment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_google_api_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_google_api_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_message_bus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_message_bus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_pipeline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_pipeline(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_trigger(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -114,6 +148,38 @@ def post_delete_channel_connection(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_enrollment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_enrollment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_google_api_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_google_api_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_message_bus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_message_bus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_pipeline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_pipeline(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_trigger(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -138,6 +204,22 @@ def post_get_channel_connection(self, response): logging.log(f"Received response: {response}") return response + def pre_get_enrollment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_enrollment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_google_api_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_google_api_source(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_google_channel_config(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -146,6 +228,22 @@ def post_get_google_channel_config(self, response): logging.log(f"Received response: {response}") return response + def pre_get_message_bus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_message_bus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_pipeline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_pipeline(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_provider(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -178,6 +276,46 @@ def post_list_channels(self, response): logging.log(f"Received response: {response}") return response + def pre_list_enrollments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_enrollments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_google_api_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_google_api_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_message_bus_enrollments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_message_bus_enrollments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_message_buses(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_message_buses(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_pipelines(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_pipelines(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_providers(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -202,6 +340,22 @@ def post_update_channel(self, response): logging.log(f"Received response: {response}") return response + def pre_update_enrollment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_enrollment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_google_api_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_google_api_source(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_google_channel_config(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -210,6 +364,22 @@ def post_update_google_channel_config(self, response): logging.log(f"Received response: {response}") return response + def pre_update_message_bus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_message_bus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_pipeline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_pipeline(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_trigger(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -270,22 +440,22 @@ def post_create_channel_connection( """ return response - def pre_create_trigger( + def pre_create_enrollment( self, - request: eventarc.CreateTriggerRequest, + request: eventarc.CreateEnrollmentRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.CreateTriggerRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_trigger + ) -> Tuple[eventarc.CreateEnrollmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_enrollment Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_create_trigger( + def post_create_enrollment( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for create_trigger + """Post-rpc interceptor for create_enrollment Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -293,22 +463,22 @@ def post_create_trigger( """ return response - def pre_delete_channel( + def pre_create_google_api_source( self, - request: eventarc.DeleteChannelRequest, + request: eventarc.CreateGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.DeleteChannelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_channel + ) -> Tuple[eventarc.CreateGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_google_api_source Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_delete_channel( + def post_create_google_api_source( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_channel + """Post-rpc interceptor for create_google_api_source Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -316,22 +486,22 @@ def post_delete_channel( """ return response - def pre_delete_channel_connection( + def pre_create_message_bus( self, - request: eventarc.DeleteChannelConnectionRequest, + request: eventarc.CreateMessageBusRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.DeleteChannelConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_channel_connection + ) -> Tuple[eventarc.CreateMessageBusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_message_bus Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_delete_channel_connection( + def post_create_message_bus( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_channel_connection + """Post-rpc interceptor for create_message_bus Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -339,22 +509,22 @@ def post_delete_channel_connection( """ return response - def pre_delete_trigger( + def pre_create_pipeline( self, - request: eventarc.DeleteTriggerRequest, + request: eventarc.CreatePipelineRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.DeleteTriggerRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_trigger + ) -> Tuple[eventarc.CreatePipelineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_pipeline Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_delete_trigger( + def post_create_pipeline( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_trigger + """Post-rpc interceptor for create_pipeline Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -362,18 +532,22 @@ def post_delete_trigger( """ return response - def pre_get_channel( - self, request: eventarc.GetChannelRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[eventarc.GetChannelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_channel + def pre_create_trigger( + self, + request: eventarc.CreateTriggerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.CreateTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_trigger Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_get_channel(self, response: channel.Channel) -> channel.Channel: - """Post-rpc interceptor for get_channel + def post_create_trigger( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_trigger Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -381,22 +555,22 @@ def post_get_channel(self, response: channel.Channel) -> channel.Channel: """ return response - def pre_get_channel_connection( + def pre_delete_channel( self, - request: eventarc.GetChannelConnectionRequest, + request: eventarc.DeleteChannelRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.GetChannelConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_channel_connection + ) -> Tuple[eventarc.DeleteChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_channel Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_get_channel_connection( - self, response: channel_connection.ChannelConnection - ) -> channel_connection.ChannelConnection: - """Post-rpc interceptor for get_channel_connection + def post_delete_channel( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_channel Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -404,22 +578,22 @@ def post_get_channel_connection( """ return response - def pre_get_google_channel_config( + def pre_delete_channel_connection( self, - request: eventarc.GetGoogleChannelConfigRequest, + request: eventarc.DeleteChannelConnectionRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.GetGoogleChannelConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_google_channel_config + ) -> Tuple[eventarc.DeleteChannelConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_channel_connection Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_get_google_channel_config( - self, response: google_channel_config.GoogleChannelConfig - ) -> google_channel_config.GoogleChannelConfig: - """Post-rpc interceptor for get_google_channel_config + def post_delete_channel_connection( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_channel_connection Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -427,18 +601,22 @@ def post_get_google_channel_config( """ return response - def pre_get_provider( - self, request: eventarc.GetProviderRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[eventarc.GetProviderRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_provider + def pre_delete_enrollment( + self, + request: eventarc.DeleteEnrollmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.DeleteEnrollmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_enrollment Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_get_provider(self, response: discovery.Provider) -> discovery.Provider: - """Post-rpc interceptor for get_provider + def post_delete_enrollment( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_enrollment Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -446,18 +624,22 @@ def post_get_provider(self, response: discovery.Provider) -> discovery.Provider: """ return response - def pre_get_trigger( - self, request: eventarc.GetTriggerRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[eventarc.GetTriggerRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_trigger + def pre_delete_google_api_source( + self, + request: eventarc.DeleteGoogleApiSourceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.DeleteGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_google_api_source Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_get_trigger(self, response: trigger.Trigger) -> trigger.Trigger: - """Post-rpc interceptor for get_trigger + def post_delete_google_api_source( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_google_api_source Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -465,22 +647,22 @@ def post_get_trigger(self, response: trigger.Trigger) -> trigger.Trigger: """ return response - def pre_list_channel_connections( + def pre_delete_message_bus( self, - request: eventarc.ListChannelConnectionsRequest, + request: eventarc.DeleteMessageBusRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.ListChannelConnectionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_channel_connections + ) -> Tuple[eventarc.DeleteMessageBusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_message_bus Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_list_channel_connections( - self, response: eventarc.ListChannelConnectionsResponse - ) -> eventarc.ListChannelConnectionsResponse: - """Post-rpc interceptor for list_channel_connections + def post_delete_message_bus( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_message_bus Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -488,20 +670,22 @@ def post_list_channel_connections( """ return response - def pre_list_channels( - self, request: eventarc.ListChannelsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[eventarc.ListChannelsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_channels + def pre_delete_pipeline( + self, + request: eventarc.DeletePipelineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.DeletePipelineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_pipeline Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_list_channels( - self, response: eventarc.ListChannelsResponse - ) -> eventarc.ListChannelsResponse: - """Post-rpc interceptor for list_channels + def post_delete_pipeline( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_pipeline Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -509,22 +693,22 @@ def post_list_channels( """ return response - def pre_list_providers( + def pre_delete_trigger( self, - request: eventarc.ListProvidersRequest, + request: eventarc.DeleteTriggerRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.ListProvidersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_providers + ) -> Tuple[eventarc.DeleteTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_trigger Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_list_providers( - self, response: eventarc.ListProvidersResponse - ) -> eventarc.ListProvidersResponse: - """Post-rpc interceptor for list_providers + def post_delete_trigger( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_trigger Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -532,20 +716,18 @@ def post_list_providers( """ return response - def pre_list_triggers( - self, request: eventarc.ListTriggersRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[eventarc.ListTriggersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_triggers + def pre_get_channel( + self, request: eventarc.GetChannelRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[eventarc.GetChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_channel Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_list_triggers( - self, response: eventarc.ListTriggersResponse - ) -> eventarc.ListTriggersResponse: - """Post-rpc interceptor for list_triggers + def post_get_channel(self, response: channel.Channel) -> channel.Channel: + """Post-rpc interceptor for get_channel Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -553,22 +735,22 @@ def post_list_triggers( """ return response - def pre_update_channel( + def pre_get_channel_connection( self, - request: eventarc.UpdateChannelRequest, + request: eventarc.GetChannelConnectionRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.UpdateChannelRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_channel + ) -> Tuple[eventarc.GetChannelConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_channel_connection Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_update_channel( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_channel + def post_get_channel_connection( + self, response: channel_connection.ChannelConnection + ) -> channel_connection.ChannelConnection: + """Post-rpc interceptor for get_channel_connection Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -576,22 +758,22 @@ def post_update_channel( """ return response - def pre_update_google_channel_config( + def pre_get_enrollment( self, - request: eventarc.UpdateGoogleChannelConfigRequest, + request: eventarc.GetEnrollmentRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.UpdateGoogleChannelConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_google_channel_config + ) -> Tuple[eventarc.GetEnrollmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_enrollment Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_update_google_channel_config( - self, response: gce_google_channel_config.GoogleChannelConfig - ) -> gce_google_channel_config.GoogleChannelConfig: - """Post-rpc interceptor for update_google_channel_config + def post_get_enrollment( + self, response: enrollment.Enrollment + ) -> enrollment.Enrollment: + """Post-rpc interceptor for get_enrollment Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -599,22 +781,22 @@ def post_update_google_channel_config( """ return response - def pre_update_trigger( + def pre_get_google_api_source( self, - request: eventarc.UpdateTriggerRequest, + request: eventarc.GetGoogleApiSourceRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[eventarc.UpdateTriggerRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_trigger + ) -> Tuple[eventarc.GetGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_google_api_source Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_update_trigger( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_trigger + def post_get_google_api_source( + self, response: google_api_source.GoogleApiSource + ) -> google_api_source.GoogleApiSource: + """Post-rpc interceptor for get_google_api_source Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -622,22 +804,22 @@ def post_update_trigger( """ return response - def pre_get_location( + def pre_get_google_channel_config( self, - request: locations_pb2.GetLocationRequest, + request: eventarc.GetGoogleChannelConfigRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location + ) -> Tuple[eventarc.GetGoogleChannelConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_google_channel_config Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location + def post_get_google_channel_config( + self, response: google_channel_config.GoogleChannelConfig + ) -> google_channel_config.GoogleChannelConfig: + """Post-rpc interceptor for get_google_channel_config Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -645,22 +827,22 @@ def post_get_location( """ return response - def pre_list_locations( + def pre_get_message_bus( self, - request: locations_pb2.ListLocationsRequest, + request: eventarc.GetMessageBusRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations + ) -> Tuple[eventarc.GetMessageBusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_message_bus Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations + def post_get_message_bus( + self, response: message_bus.MessageBus + ) -> message_bus.MessageBus: + """Post-rpc interceptor for get_message_bus Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -668,20 +850,79 @@ def post_list_locations( """ return response - def pre_get_iam_policy( + def pre_get_pipeline( + self, request: eventarc.GetPipelineRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[eventarc.GetPipelineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_pipeline + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_pipeline(self, response: pipeline.Pipeline) -> pipeline.Pipeline: + """Post-rpc interceptor for get_pipeline + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_provider( + self, request: eventarc.GetProviderRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[eventarc.GetProviderRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_provider + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_provider(self, response: discovery.Provider) -> discovery.Provider: + """Post-rpc interceptor for get_provider + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_trigger( + self, request: eventarc.GetTriggerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[eventarc.GetTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_trigger(self, response: trigger.Trigger) -> trigger.Trigger: + """Post-rpc interceptor for get_trigger + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_channel_connections( self, - request: iam_policy_pb2.GetIamPolicyRequest, + request: eventarc.ListChannelConnectionsRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy + ) -> Tuple[eventarc.ListChannelConnectionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_channel_connections Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy + def post_list_channel_connections( + self, response: eventarc.ListChannelConnectionsResponse + ) -> eventarc.ListChannelConnectionsResponse: + """Post-rpc interceptor for list_channel_connections Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -689,20 +930,43 @@ def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """ return response - def pre_set_iam_policy( + def pre_list_channels( + self, request: eventarc.ListChannelsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[eventarc.ListChannelsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_channels + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_channels( + self, response: eventarc.ListChannelsResponse + ) -> eventarc.ListChannelsResponse: + """Post-rpc interceptor for list_channels + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_enrollments( self, - request: iam_policy_pb2.SetIamPolicyRequest, + request: eventarc.ListEnrollmentsRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy + ) -> Tuple[eventarc.ListEnrollmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_enrollments Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy + def post_list_enrollments( + self, response: eventarc.ListEnrollmentsResponse + ) -> eventarc.ListEnrollmentsResponse: + """Post-rpc interceptor for list_enrollments Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -710,22 +974,22 @@ def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """ return response - def pre_test_iam_permissions( + def pre_list_google_api_sources( self, - request: iam_policy_pb2.TestIamPermissionsRequest, + request: eventarc.ListGoogleApiSourcesRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions + ) -> Tuple[eventarc.ListGoogleApiSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_google_api_sources Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions + def post_list_google_api_sources( + self, response: eventarc.ListGoogleApiSourcesResponse + ) -> eventarc.ListGoogleApiSourcesResponse: + """Post-rpc interceptor for list_google_api_sources Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -733,20 +997,22 @@ def post_test_iam_permissions( """ return response - def pre_cancel_operation( + def pre_list_message_bus_enrollments( self, - request: operations_pb2.CancelOperationRequest, + request: eventarc.ListMessageBusEnrollmentsRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation + ) -> Tuple[eventarc.ListMessageBusEnrollmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_message_bus_enrollments Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_cancel_operation(self, response: None) -> None: - """Post-rpc interceptor for cancel_operation + def post_list_message_bus_enrollments( + self, response: eventarc.ListMessageBusEnrollmentsResponse + ) -> eventarc.ListMessageBusEnrollmentsResponse: + """Post-rpc interceptor for list_message_bus_enrollments Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -754,20 +1020,22 @@ def post_cancel_operation(self, response: None) -> None: """ return response - def pre_delete_operation( + def pre_list_message_buses( self, - request: operations_pb2.DeleteOperationRequest, + request: eventarc.ListMessageBusesRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation + ) -> Tuple[eventarc.ListMessageBusesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_message_buses Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_delete_operation(self, response: None) -> None: - """Post-rpc interceptor for delete_operation + def post_list_message_buses( + self, response: eventarc.ListMessageBusesResponse + ) -> eventarc.ListMessageBusesResponse: + """Post-rpc interceptor for list_message_buses Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -775,22 +1043,22 @@ def post_delete_operation(self, response: None) -> None: """ return response - def pre_get_operation( + def pre_list_pipelines( self, - request: operations_pb2.GetOperationRequest, + request: eventarc.ListPipelinesRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation + ) -> Tuple[eventarc.ListPipelinesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_pipelines Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation + def post_list_pipelines( + self, response: eventarc.ListPipelinesResponse + ) -> eventarc.ListPipelinesResponse: + """Post-rpc interceptor for list_pipelines Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -798,22 +1066,22 @@ def post_get_operation( """ return response - def pre_list_operations( + def pre_list_providers( self, - request: operations_pb2.ListOperationsRequest, + request: eventarc.ListProvidersRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations + ) -> Tuple[eventarc.ListProvidersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_providers Override in a subclass to manipulate the request or metadata before they are sent to the Eventarc server. """ return request, metadata - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations + def post_list_providers( + self, response: eventarc.ListProvidersResponse + ) -> eventarc.ListProvidersResponse: + """Post-rpc interceptor for list_providers Override in a subclass to manipulate the response after it is returned by the Eventarc server but before @@ -821,154 +1089,2479 @@ def post_list_operations( """ return response + def pre_list_triggers( + self, request: eventarc.ListTriggersRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[eventarc.ListTriggersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_triggers -@dataclasses.dataclass -class EventarcRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EventarcRestInterceptor + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + def post_list_triggers( + self, response: eventarc.ListTriggersResponse + ) -> eventarc.ListTriggersResponse: + """Post-rpc interceptor for list_triggers -class EventarcRestTransport(_BaseEventarcRestTransport): - """REST backend synchronous transport for Eventarc. + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response - Eventarc allows users to subscribe to various events that are - provided by Google Cloud services and forward them to supported - destinations. + def pre_update_channel( + self, + request: eventarc.UpdateChannelRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.UpdateChannelRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_channel - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata - It sends JSON representations of protocol buffers over HTTP/1.1 - """ + def post_update_channel( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_channel - def __init__( - self, - *, - host: str = "eventarc.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[EventarcRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response - Args: - host (Optional[str]): - The hostname to connect to (default: 'eventarc.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. + def pre_update_enrollment( + self, + request: eventarc.UpdateEnrollmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.UpdateEnrollmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_enrollment - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - 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. + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. """ - # 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 - ) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or EventarcRestInterceptor() - self._prep_wrapped_messages(client_info) + return request, metadata + + def post_update_enrollment( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_enrollment + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_google_api_source( + self, + request: eventarc.UpdateGoogleApiSourceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.UpdateGoogleApiSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_google_api_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_google_api_source( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_google_api_source + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_google_channel_config( + self, + request: eventarc.UpdateGoogleChannelConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.UpdateGoogleChannelConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_google_channel_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_google_channel_config( + self, response: gce_google_channel_config.GoogleChannelConfig + ) -> gce_google_channel_config.GoogleChannelConfig: + """Post-rpc interceptor for update_google_channel_config + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_message_bus( + self, + request: eventarc.UpdateMessageBusRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.UpdateMessageBusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_message_bus + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_message_bus( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_message_bus + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_pipeline( + self, + request: eventarc.UpdatePipelineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.UpdatePipelineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_pipeline + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_pipeline( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_pipeline + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_update_trigger( + self, + request: eventarc.UpdateTriggerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[eventarc.UpdateTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_update_trigger( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_trigger + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Eventarc server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Eventarc server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EventarcRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EventarcRestInterceptor + + +class EventarcRestTransport(_BaseEventarcRestTransport): + """REST backend synchronous transport for Eventarc. + + Eventarc allows users to subscribe to various events that are + provided by Google Cloud services and forward them to supported + destinations. + + 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 = "eventarc.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[EventarcRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'eventarc.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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + 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 + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or EventarcRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateChannel( + _BaseEventarcRestTransport._BaseCreateChannel, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.CreateChannel") + + @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: eventarc.CreateChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create channel method over HTTP. + + Args: + request (~.eventarc.CreateChannelRequest): + The request object. The request message for the + CreateChannel method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseCreateChannel._get_http_options() + ) + request, metadata = self._interceptor.pre_create_channel(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseCreateChannel._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseEventarcRestTransport._BaseCreateChannel._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseCreateChannel._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._CreateChannel._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_channel(resp) + return resp + + class _CreateChannelConnection( + _BaseEventarcRestTransport._BaseCreateChannelConnection, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.CreateChannelConnection") + + @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: eventarc.CreateChannelConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create channel connection method over HTTP. + + Args: + request (~.eventarc.CreateChannelConnectionRequest): + The request object. The request message for the + CreateChannelConnection method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseCreateChannelConnection._get_http_options() + ) + request, metadata = self._interceptor.pre_create_channel_connection( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_transcoded_request( + http_options, request + ) + + body = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_query_params_json( + transcoded_request + ) + + # Send the request + response = EventarcRestTransport._CreateChannelConnection._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_channel_connection(resp) + return resp + + class _CreateEnrollment( + _BaseEventarcRestTransport._BaseCreateEnrollment, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.CreateEnrollment") + + @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: eventarc.CreateEnrollmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create enrollment method over HTTP. + + Args: + request (~.eventarc.CreateEnrollmentRequest): + The request object. The request message for the + CreateEnrollment method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseCreateEnrollment._get_http_options() + ) + request, metadata = self._interceptor.pre_create_enrollment( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseCreateEnrollment._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseEventarcRestTransport._BaseCreateEnrollment._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseCreateEnrollment._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._CreateEnrollment._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_enrollment(resp) + return resp + + class _CreateGoogleApiSource( + _BaseEventarcRestTransport._BaseCreateGoogleApiSource, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.CreateGoogleApiSource") + + @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: eventarc.CreateGoogleApiSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create google api source method over HTTP. + + Args: + request (~.eventarc.CreateGoogleApiSourceRequest): + The request object. The request message for the + CreateGoogleApiSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_http_options() + ) + request, metadata = self._interceptor.pre_create_google_api_source( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_transcoded_request( + http_options, request + ) + + body = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_query_params_json( + transcoded_request + ) + + # Send the request + response = EventarcRestTransport._CreateGoogleApiSource._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_google_api_source(resp) + return resp + + class _CreateMessageBus( + _BaseEventarcRestTransport._BaseCreateMessageBus, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.CreateMessageBus") + + @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: eventarc.CreateMessageBusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create message bus method over HTTP. + + Args: + request (~.eventarc.CreateMessageBusRequest): + The request object. The request message for the + CreateMessageBus method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseCreateMessageBus._get_http_options() + ) + request, metadata = self._interceptor.pre_create_message_bus( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseCreateMessageBus._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseEventarcRestTransport._BaseCreateMessageBus._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseCreateMessageBus._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._CreateMessageBus._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_message_bus(resp) + return resp + + class _CreatePipeline( + _BaseEventarcRestTransport._BaseCreatePipeline, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.CreatePipeline") + + @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: eventarc.CreatePipelineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create pipeline method over HTTP. + + Args: + request (~.eventarc.CreatePipelineRequest): + The request object. The request message for the + CreatePipeline method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseCreatePipeline._get_http_options() + ) + request, metadata = self._interceptor.pre_create_pipeline(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseCreatePipeline._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseEventarcRestTransport._BaseCreatePipeline._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseCreatePipeline._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._CreatePipeline._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_pipeline(resp) + return resp + + class _CreateTrigger( + _BaseEventarcRestTransport._BaseCreateTrigger, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.CreateTrigger") + + @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: eventarc.CreateTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create trigger method over HTTP. + + Args: + request (~.eventarc.CreateTriggerRequest): + The request object. The request message for the + CreateTrigger method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseCreateTrigger._get_http_options() + ) + request, metadata = self._interceptor.pre_create_trigger(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseCreateTrigger._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseEventarcRestTransport._BaseCreateTrigger._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseCreateTrigger._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._CreateTrigger._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_trigger(resp) + return resp + + class _DeleteChannel( + _BaseEventarcRestTransport._BaseDeleteChannel, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.DeleteChannel") + + @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: eventarc.DeleteChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete channel method over HTTP. + + Args: + request (~.eventarc.DeleteChannelRequest): + The request object. The request message for the + DeleteChannel method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseDeleteChannel._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_channel(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseDeleteChannel._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseDeleteChannel._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._DeleteChannel._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_channel(resp) + return resp + + class _DeleteChannelConnection( + _BaseEventarcRestTransport._BaseDeleteChannelConnection, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.DeleteChannelConnection") + + @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: eventarc.DeleteChannelConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete channel connection method over HTTP. + + Args: + request (~.eventarc.DeleteChannelConnectionRequest): + The request object. The request message for the + DeleteChannelConnection method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_channel_connection( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_query_params_json( + transcoded_request + ) + + # Send the request + response = EventarcRestTransport._DeleteChannelConnection._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_channel_connection(resp) + return resp + + class _DeleteEnrollment( + _BaseEventarcRestTransport._BaseDeleteEnrollment, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.DeleteEnrollment") + + @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: eventarc.DeleteEnrollmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete enrollment method over HTTP. + + Args: + request (~.eventarc.DeleteEnrollmentRequest): + The request object. The request message for the + DeleteEnrollment method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseDeleteEnrollment._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_enrollment( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteEnrollment._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseDeleteEnrollment._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._DeleteEnrollment._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_enrollment(resp) + return resp + + class _DeleteGoogleApiSource( + _BaseEventarcRestTransport._BaseDeleteGoogleApiSource, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.DeleteGoogleApiSource") + + @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: eventarc.DeleteGoogleApiSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete google api source method over HTTP. + + Args: + request (~.eventarc.DeleteGoogleApiSourceRequest): + The request object. The request message for the + DeleteGoogleApiSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_google_api_source( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_query_params_json( + transcoded_request + ) + + # Send the request + response = EventarcRestTransport._DeleteGoogleApiSource._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_google_api_source(resp) + return resp + + class _DeleteMessageBus( + _BaseEventarcRestTransport._BaseDeleteMessageBus, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.DeleteMessageBus") + + @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: eventarc.DeleteMessageBusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete message bus method over HTTP. + + Args: + request (~.eventarc.DeleteMessageBusRequest): + The request object. The request message for the + DeleteMessageBus method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseDeleteMessageBus._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_message_bus( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseDeleteMessageBus._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseDeleteMessageBus._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._DeleteMessageBus._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_message_bus(resp) + return resp + + class _DeletePipeline( + _BaseEventarcRestTransport._BaseDeletePipeline, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.DeletePipeline") + + @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: eventarc.DeletePipelineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete pipeline method over HTTP. + + Args: + request (~.eventarc.DeletePipelineRequest): + The request object. The request message for the + DeletePipeline method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseDeletePipeline._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_pipeline(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseDeletePipeline._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseDeletePipeline._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._DeletePipeline._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_pipeline(resp) + return resp + + class _DeleteTrigger( + _BaseEventarcRestTransport._BaseDeleteTrigger, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.DeleteTrigger") + + @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: eventarc.DeleteTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete trigger method over HTTP. + + Args: + request (~.eventarc.DeleteTriggerRequest): + The request object. The request message for the + DeleteTrigger method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseDeleteTrigger._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_trigger(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseDeleteTrigger._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseDeleteTrigger._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._DeleteTrigger._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_trigger(resp) + return resp + + class _GetChannel(_BaseEventarcRestTransport._BaseGetChannel, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetChannel") + + @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: eventarc.GetChannelRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> channel.Channel: + r"""Call the get channel method over HTTP. + + Args: + request (~.eventarc.GetChannelRequest): + The request object. The request message for the + GetChannel method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.channel.Channel: + A representation of the Channel + resource. A Channel is a resource on + which event providers publish their + events. The published events are + delivered through the transport + associated with the channel. Note that a + channel is associated with exactly one + event provider. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseGetChannel._get_http_options() + ) + request, metadata = self._interceptor.pre_get_channel(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetChannel._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseGetChannel._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._GetChannel._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 = channel.Channel() + pb_resp = channel.Channel.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_channel(resp) + return resp + + class _GetChannelConnection( + _BaseEventarcRestTransport._BaseGetChannelConnection, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.GetChannelConnection") + + @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: eventarc.GetChannelConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> channel_connection.ChannelConnection: + r"""Call the get channel connection method over HTTP. + + Args: + request (~.eventarc.GetChannelConnectionRequest): + The request object. The request message for the + GetChannelConnection method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.channel_connection.ChannelConnection: + A representation of the + ChannelConnection resource. A + ChannelConnection is a resource which + event providers create during the + activation process to establish a + connection between the provider and the + subscriber channel. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseGetChannelConnection._get_http_options() + ) + request, metadata = self._interceptor.pre_get_channel_connection( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseGetChannelConnection._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetChannelConnection._get_query_params_json( + transcoded_request + ) + + # Send the request + response = EventarcRestTransport._GetChannelConnection._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 = channel_connection.ChannelConnection() + pb_resp = channel_connection.ChannelConnection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_channel_connection(resp) + return resp + + class _GetEnrollment( + _BaseEventarcRestTransport._BaseGetEnrollment, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.GetEnrollment") + + @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: eventarc.GetEnrollmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> enrollment.Enrollment: + r"""Call the get enrollment method over HTTP. + + Args: + request (~.eventarc.GetEnrollmentRequest): + The request object. The request message for the + GetEnrollment method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.enrollment.Enrollment: + An enrollment represents a + subscription for messages on a + particular message bus. It defines a + matching criteria for messages on the + bus and the subscriber endpoint where + matched messages should be delivered. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseGetEnrollment._get_http_options() + ) + request, metadata = self._interceptor.pre_get_enrollment(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetEnrollment._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseGetEnrollment._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = EventarcRestTransport._GetEnrollment._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 = enrollment.Enrollment() + pb_resp = enrollment.Enrollment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_enrollment(resp) + return resp + + class _GetGoogleApiSource( + _BaseEventarcRestTransport._BaseGetGoogleApiSource, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.GetGoogleApiSource") + + @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: eventarc.GetGoogleApiSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> google_api_source.GoogleApiSource: + r"""Call the get google api source method over HTTP. + + Args: + request (~.eventarc.GetGoogleApiSourceRequest): + The request object. The request message for the + GetGoogleApiSource method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.google_api_source.GoogleApiSource: + A GoogleApiSource represents a + subscription of 1P events from a + MessageBus. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_http_options() + ) + request, metadata = self._interceptor.pre_get_google_api_source( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_query_params_json( + transcoded_request + ) + + # Send the request + response = EventarcRestTransport._GetGoogleApiSource._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 = google_api_source.GoogleApiSource() + pb_resp = google_api_source.GoogleApiSource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_google_api_source(resp) + return resp + + class _GetGoogleChannelConfig( + _BaseEventarcRestTransport._BaseGetGoogleChannelConfig, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.GetGoogleChannelConfig") + + @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: eventarc.GetGoogleChannelConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> google_channel_config.GoogleChannelConfig: + r"""Call the get google channel config method over HTTP. + + Args: + request (~.eventarc.GetGoogleChannelConfigRequest): + The request object. The request message for the + GetGoogleChannelConfig method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.google_channel_config.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_http_options() + ) + request, metadata = self._interceptor.pre_get_google_channel_config( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_query_params_json( + transcoded_request + ) + + # Send the request + response = EventarcRestTransport._GetGoogleChannelConfig._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 = google_channel_config.GoogleChannelConfig() + pb_resp = google_channel_config.GoogleChannelConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_google_channel_config(resp) + return resp + + class _GetMessageBus( + _BaseEventarcRestTransport._BaseGetMessageBus, EventarcRestStub + ): + def __hash__(self): + return hash("EventarcRestTransport.GetMessageBus") + + @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: eventarc.GetMessageBusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message_bus.MessageBus: + r"""Call the get message bus method over HTTP. + + Args: + request (~.eventarc.GetMessageBusRequest): + The request object. The request message for the + GetMessageBus method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. + Returns: + ~.message_bus.MessageBus: + MessageBus for the messages flowing + through the system. The admin has + visibility and control over the messages + being published and consumed and can + restrict publishers and subscribers to + only a subset of data available in the + system by defining authorization + policies. - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - "google.longrunning.Operations.CancelOperation": [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", - "body": "*", - }, - ], - "google.longrunning.Operations.DeleteOperation": [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ], - "google.longrunning.Operations.GetOperation": [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ], - "google.longrunning.Operations.ListOperations": [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - ], - } + """ - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1", + http_options = ( + _BaseEventarcRestTransport._BaseGetMessageBus._get_http_options() + ) + request, metadata = self._interceptor.pre_get_message_bus(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetMessageBus._get_transcoded_request( + http_options, request + ) ) - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseGetMessageBus._get_query_params_json( + transcoded_request + ) ) - # Return the client from cache. - return self._operations_client + # Send the request + response = EventarcRestTransport._GetMessageBus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) - class _CreateChannel( - _BaseEventarcRestTransport._BaseCreateChannel, EventarcRestStub - ): + # 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 = message_bus.MessageBus() + pb_resp = message_bus.MessageBus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_message_bus(resp) + return resp + + class _GetPipeline(_BaseEventarcRestTransport._BaseGetPipeline, EventarcRestStub): def __hash__(self): - return hash("EventarcRestTransport.CreateChannel") + return hash("EventarcRestTransport.GetPipeline") @staticmethod def _get_response( @@ -989,24 +3582,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: eventarc.CreateChannelRequest, + request: eventarc.GetPipelineRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Call the create channel method over HTTP. + ) -> pipeline.Pipeline: + r"""Call the get pipeline method over HTTP. Args: - request (~.eventarc.CreateChannelRequest): + request (~.eventarc.GetPipelineRequest): The request object. The request message for the - CreateChannel method. + GetPipeline method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1014,43 +3606,37 @@ def __call__( sent along with the request as metadata. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.pipeline.Pipeline: + A representation of the Pipeline + resource. """ http_options = ( - _BaseEventarcRestTransport._BaseCreateChannel._get_http_options() + _BaseEventarcRestTransport._BaseGetPipeline._get_http_options() ) - request, metadata = self._interceptor.pre_create_channel(request, metadata) + request, metadata = self._interceptor.pre_get_pipeline(request, metadata) transcoded_request = ( - _BaseEventarcRestTransport._BaseCreateChannel._get_transcoded_request( + _BaseEventarcRestTransport._BaseGetPipeline._get_transcoded_request( http_options, request ) ) - body = _BaseEventarcRestTransport._BaseCreateChannel._get_request_body_json( - transcoded_request - ) - # Jsonify the query params query_params = ( - _BaseEventarcRestTransport._BaseCreateChannel._get_query_params_json( + _BaseEventarcRestTransport._BaseGetPipeline._get_query_params_json( transcoded_request ) ) # Send the request - response = EventarcRestTransport._CreateChannel._get_response( + response = EventarcRestTransport._GetPipeline._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1059,16 +3645,16 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_channel(resp) + resp = pipeline.Pipeline() + pb_resp = pipeline.Pipeline.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_pipeline(resp) return resp - class _CreateChannelConnection( - _BaseEventarcRestTransport._BaseCreateChannelConnection, EventarcRestStub - ): + class _GetProvider(_BaseEventarcRestTransport._BaseGetProvider, EventarcRestStub): def __hash__(self): - return hash("EventarcRestTransport.CreateChannelConnection") + return hash("EventarcRestTransport.GetProvider") @staticmethod def _get_response( @@ -1089,24 +3675,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: eventarc.CreateChannelConnectionRequest, + request: eventarc.GetProviderRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Call the create channel connection method over HTTP. + ) -> discovery.Provider: + r"""Call the get provider method over HTTP. Args: - request (~.eventarc.CreateChannelConnectionRequest): + request (~.eventarc.GetProviderRequest): The request object. The request message for the - CreateChannelConnection method. + GetProvider method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1114,41 +3699,130 @@ def __call__( sent along with the request as metadata. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.discovery.Provider: + A representation of the Provider + resource. """ http_options = ( - _BaseEventarcRestTransport._BaseCreateChannelConnection._get_http_options() + _BaseEventarcRestTransport._BaseGetProvider._get_http_options() ) - request, metadata = self._interceptor.pre_create_channel_connection( - request, metadata + request, metadata = self._interceptor.pre_get_provider(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetProvider._get_transcoded_request( + http_options, request + ) ) - transcoded_request = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_transcoded_request( - http_options, request + + # Jsonify the query params + query_params = ( + _BaseEventarcRestTransport._BaseGetProvider._get_query_params_json( + transcoded_request + ) ) - body = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_request_body_json( - transcoded_request + # Send the request + response = EventarcRestTransport._GetProvider._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 = discovery.Provider() + pb_resp = discovery.Provider.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_provider(resp) + return resp + + class _GetTrigger(_BaseEventarcRestTransport._BaseGetTrigger, EventarcRestStub): + def __hash__(self): + return hash("EventarcRestTransport.GetTrigger") + + @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: eventarc.GetTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trigger.Trigger: + r"""Call the get trigger method over HTTP. + + Args: + request (~.eventarc.GetTriggerRequest): + The request object. The request message for the + GetTrigger method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.trigger.Trigger: + A representation of the trigger + resource. + + """ + + http_options = ( + _BaseEventarcRestTransport._BaseGetTrigger._get_http_options() + ) + request, metadata = self._interceptor.pre_get_trigger(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseGetTrigger._get_transcoded_request( + http_options, request + ) ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseCreateChannelConnection._get_query_params_json( - transcoded_request + query_params = ( + _BaseEventarcRestTransport._BaseGetTrigger._get_query_params_json( + transcoded_request + ) ) # Send the request - response = EventarcRestTransport._CreateChannelConnection._get_response( + response = EventarcRestTransport._GetTrigger._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1157,16 +3831,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_channel_connection(resp) + resp = trigger.Trigger() + pb_resp = trigger.Trigger.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_trigger(resp) return resp - class _CreateTrigger( - _BaseEventarcRestTransport._BaseCreateTrigger, EventarcRestStub + class _ListChannelConnections( + _BaseEventarcRestTransport._BaseListChannelConnections, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.CreateTrigger") + return hash("EventarcRestTransport.ListChannelConnections") @staticmethod def _get_response( @@ -1187,24 +3863,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: eventarc.CreateTriggerRequest, + request: eventarc.ListChannelConnectionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Call the create trigger method over HTTP. + ) -> eventarc.ListChannelConnectionsResponse: + r"""Call the list channel connections method over HTTP. Args: - request (~.eventarc.CreateTriggerRequest): + request (~.eventarc.ListChannelConnectionsRequest): The request object. The request message for the - CreateTrigger method. + ListChannelConnections method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1212,43 +3887,35 @@ def __call__( sent along with the request as metadata. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.eventarc.ListChannelConnectionsResponse: + The response message for the ``ListChannelConnections`` + method. """ http_options = ( - _BaseEventarcRestTransport._BaseCreateTrigger._get_http_options() + _BaseEventarcRestTransport._BaseListChannelConnections._get_http_options() ) - request, metadata = self._interceptor.pre_create_trigger(request, metadata) - transcoded_request = ( - _BaseEventarcRestTransport._BaseCreateTrigger._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_channel_connections( + request, metadata ) - - body = _BaseEventarcRestTransport._BaseCreateTrigger._get_request_body_json( - transcoded_request + transcoded_request = _BaseEventarcRestTransport._BaseListChannelConnections._get_transcoded_request( + http_options, request ) # Jsonify the query params - query_params = ( - _BaseEventarcRestTransport._BaseCreateTrigger._get_query_params_json( - transcoded_request - ) + query_params = _BaseEventarcRestTransport._BaseListChannelConnections._get_query_params_json( + transcoded_request ) # Send the request - response = EventarcRestTransport._CreateTrigger._get_response( + response = EventarcRestTransport._ListChannelConnections._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1257,16 +3924,16 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_trigger(resp) + resp = eventarc.ListChannelConnectionsResponse() + pb_resp = eventarc.ListChannelConnectionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_channel_connections(resp) return resp - class _DeleteChannel( - _BaseEventarcRestTransport._BaseDeleteChannel, EventarcRestStub - ): + class _ListChannels(_BaseEventarcRestTransport._BaseListChannels, EventarcRestStub): def __hash__(self): - return hash("EventarcRestTransport.DeleteChannel") + return hash("EventarcRestTransport.ListChannels") @staticmethod def _get_response( @@ -1292,18 +3959,18 @@ def _get_response( def __call__( self, - request: eventarc.DeleteChannelRequest, + request: eventarc.ListChannelsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete channel method over HTTP. + ) -> eventarc.ListChannelsResponse: + r"""Call the list channels method over HTTP. Args: - request (~.eventarc.DeleteChannelRequest): + request (~.eventarc.ListChannelsRequest): The request object. The request message for the - DeleteChannel method. + ListChannels method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1311,32 +3978,29 @@ def __call__( sent along with the request as metadata. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ~.eventarc.ListChannelsResponse: + The response message for the ``ListChannels`` method. """ http_options = ( - _BaseEventarcRestTransport._BaseDeleteChannel._get_http_options() + _BaseEventarcRestTransport._BaseListChannels._get_http_options() ) - request, metadata = self._interceptor.pre_delete_channel(request, metadata) + request, metadata = self._interceptor.pre_list_channels(request, metadata) transcoded_request = ( - _BaseEventarcRestTransport._BaseDeleteChannel._get_transcoded_request( + _BaseEventarcRestTransport._BaseListChannels._get_transcoded_request( http_options, request ) ) # Jsonify the query params query_params = ( - _BaseEventarcRestTransport._BaseDeleteChannel._get_query_params_json( + _BaseEventarcRestTransport._BaseListChannels._get_query_params_json( transcoded_request ) ) # Send the request - response = EventarcRestTransport._DeleteChannel._get_response( + response = EventarcRestTransport._ListChannels._get_response( self._host, metadata, query_params, @@ -1351,16 +4015,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_channel(resp) + resp = eventarc.ListChannelsResponse() + pb_resp = eventarc.ListChannelsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_channels(resp) return resp - class _DeleteChannelConnection( - _BaseEventarcRestTransport._BaseDeleteChannelConnection, EventarcRestStub + class _ListEnrollments( + _BaseEventarcRestTransport._BaseListEnrollments, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.DeleteChannelConnection") + return hash("EventarcRestTransport.ListEnrollments") @staticmethod def _get_response( @@ -1386,18 +4052,18 @@ def _get_response( def __call__( self, - request: eventarc.DeleteChannelConnectionRequest, + request: eventarc.ListEnrollmentsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete channel connection method over HTTP. + ) -> eventarc.ListEnrollmentsResponse: + r"""Call the list enrollments method over HTTP. Args: - request (~.eventarc.DeleteChannelConnectionRequest): + request (~.eventarc.ListEnrollmentsRequest): The request object. The request message for the - DeleteChannelConnection method. + ListEnrollments method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1405,30 +4071,31 @@ def __call__( sent along with the request as metadata. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ~.eventarc.ListEnrollmentsResponse: + The response message for the ``ListEnrollments`` method. """ http_options = ( - _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_http_options() + _BaseEventarcRestTransport._BaseListEnrollments._get_http_options() ) - request, metadata = self._interceptor.pre_delete_channel_connection( + request, metadata = self._interceptor.pre_list_enrollments( request, metadata ) - transcoded_request = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_transcoded_request( - http_options, request + transcoded_request = ( + _BaseEventarcRestTransport._BaseListEnrollments._get_transcoded_request( + http_options, request + ) ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_query_params_json( - transcoded_request + query_params = ( + _BaseEventarcRestTransport._BaseListEnrollments._get_query_params_json( + transcoded_request + ) ) # Send the request - response = EventarcRestTransport._DeleteChannelConnection._get_response( + response = EventarcRestTransport._ListEnrollments._get_response( self._host, metadata, query_params, @@ -1443,16 +4110,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_channel_connection(resp) + resp = eventarc.ListEnrollmentsResponse() + pb_resp = eventarc.ListEnrollmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_enrollments(resp) return resp - class _DeleteTrigger( - _BaseEventarcRestTransport._BaseDeleteTrigger, EventarcRestStub + class _ListGoogleApiSources( + _BaseEventarcRestTransport._BaseListGoogleApiSources, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.DeleteTrigger") + return hash("EventarcRestTransport.ListGoogleApiSources") @staticmethod def _get_response( @@ -1478,18 +4147,18 @@ def _get_response( def __call__( self, - request: eventarc.DeleteTriggerRequest, + request: eventarc.ListGoogleApiSourcesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete trigger method over HTTP. + ) -> eventarc.ListGoogleApiSourcesResponse: + r"""Call the list google api sources method over HTTP. Args: - request (~.eventarc.DeleteTriggerRequest): + request (~.eventarc.ListGoogleApiSourcesRequest): The request object. The request message for the - DeleteTrigger method. + ListGoogleApiSources method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1497,32 +4166,29 @@ def __call__( sent along with the request as metadata. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + ~.eventarc.ListGoogleApiSourcesResponse: + The response message for the ``ListGoogleApiSources`` + method. """ http_options = ( - _BaseEventarcRestTransport._BaseDeleteTrigger._get_http_options() + _BaseEventarcRestTransport._BaseListGoogleApiSources._get_http_options() ) - request, metadata = self._interceptor.pre_delete_trigger(request, metadata) - transcoded_request = ( - _BaseEventarcRestTransport._BaseDeleteTrigger._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_google_api_sources( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_transcoded_request( + http_options, request ) # Jsonify the query params - query_params = ( - _BaseEventarcRestTransport._BaseDeleteTrigger._get_query_params_json( - transcoded_request - ) + query_params = _BaseEventarcRestTransport._BaseListGoogleApiSources._get_query_params_json( + transcoded_request ) # Send the request - response = EventarcRestTransport._DeleteTrigger._get_response( + response = EventarcRestTransport._ListGoogleApiSources._get_response( self._host, metadata, query_params, @@ -1537,14 +4203,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_trigger(resp) + resp = eventarc.ListGoogleApiSourcesResponse() + pb_resp = eventarc.ListGoogleApiSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_google_api_sources(resp) return resp - class _GetChannel(_BaseEventarcRestTransport._BaseGetChannel, EventarcRestStub): + class _ListMessageBusEnrollments( + _BaseEventarcRestTransport._BaseListMessageBusEnrollments, EventarcRestStub + ): def __hash__(self): - return hash("EventarcRestTransport.GetChannel") + return hash("EventarcRestTransport.ListMessageBusEnrollments") @staticmethod def _get_response( @@ -1570,56 +4240,49 @@ def _get_response( def __call__( self, - request: eventarc.GetChannelRequest, + request: eventarc.ListMessageBusEnrollmentsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> channel.Channel: - r"""Call the get channel method over HTTP. + ) -> eventarc.ListMessageBusEnrollmentsResponse: + r"""Call the list message bus + enrollments method over HTTP. - Args: - request (~.eventarc.GetChannelRequest): - The request object. The request message for the - GetChannel method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + Args: + request (~.eventarc.ListMessageBusEnrollmentsRequest): + The request object. The request message for the + ``ListMessageBusEnrollments`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. - Returns: - ~.channel.Channel: - A representation of the Channel - resource. A Channel is a resource on - which event providers publish their - events. The published events are - delivered through the transport - associated with the channel. Note that a - channel is associated with exactly one - event provider. + Returns: + ~.eventarc.ListMessageBusEnrollmentsResponse: + The response message for the + ``ListMessageBusEnrollments`` method.\` """ http_options = ( - _BaseEventarcRestTransport._BaseGetChannel._get_http_options() + _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_http_options() ) - request, metadata = self._interceptor.pre_get_channel(request, metadata) - transcoded_request = ( - _BaseEventarcRestTransport._BaseGetChannel._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_message_bus_enrollments( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_transcoded_request( + http_options, request ) # Jsonify the query params - query_params = ( - _BaseEventarcRestTransport._BaseGetChannel._get_query_params_json( - transcoded_request - ) + query_params = _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_query_params_json( + transcoded_request ) # Send the request - response = EventarcRestTransport._GetChannel._get_response( + response = EventarcRestTransport._ListMessageBusEnrollments._get_response( self._host, metadata, query_params, @@ -1634,18 +4297,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = channel.Channel() - pb_resp = channel.Channel.pb(resp) + resp = eventarc.ListMessageBusEnrollmentsResponse() + pb_resp = eventarc.ListMessageBusEnrollmentsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_channel(resp) + resp = self._interceptor.post_list_message_bus_enrollments(resp) return resp - class _GetChannelConnection( - _BaseEventarcRestTransport._BaseGetChannelConnection, EventarcRestStub + class _ListMessageBuses( + _BaseEventarcRestTransport._BaseListMessageBuses, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.GetChannelConnection") + return hash("EventarcRestTransport.ListMessageBuses") @staticmethod def _get_response( @@ -1671,18 +4334,18 @@ def _get_response( def __call__( self, - request: eventarc.GetChannelConnectionRequest, + request: eventarc.ListMessageBusesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> channel_connection.ChannelConnection: - r"""Call the get channel connection method over HTTP. + ) -> eventarc.ListMessageBusesResponse: + r"""Call the list message buses method over HTTP. Args: - request (~.eventarc.GetChannelConnectionRequest): + request (~.eventarc.ListMessageBusesRequest): The request object. The request message for the - GetChannelConnection method. + ListMessageBuses method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1690,34 +4353,31 @@ def __call__( sent along with the request as metadata. Returns: - ~.channel_connection.ChannelConnection: - A representation of the - ChannelConnection resource. A - ChannelConnection is a resource which - event providers create during the - activation process to establish a - connection between the provider and the - subscriber channel. + ~.eventarc.ListMessageBusesResponse: + The response message for the ``ListMessageBuses`` + method. """ http_options = ( - _BaseEventarcRestTransport._BaseGetChannelConnection._get_http_options() + _BaseEventarcRestTransport._BaseListMessageBuses._get_http_options() ) - request, metadata = self._interceptor.pre_get_channel_connection( + request, metadata = self._interceptor.pre_list_message_buses( request, metadata ) - transcoded_request = _BaseEventarcRestTransport._BaseGetChannelConnection._get_transcoded_request( + transcoded_request = _BaseEventarcRestTransport._BaseListMessageBuses._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetChannelConnection._get_query_params_json( - transcoded_request + query_params = ( + _BaseEventarcRestTransport._BaseListMessageBuses._get_query_params_json( + transcoded_request + ) ) # Send the request - response = EventarcRestTransport._GetChannelConnection._get_response( + response = EventarcRestTransport._ListMessageBuses._get_response( self._host, metadata, query_params, @@ -1732,18 +4392,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = channel_connection.ChannelConnection() - pb_resp = channel_connection.ChannelConnection.pb(resp) + resp = eventarc.ListMessageBusesResponse() + pb_resp = eventarc.ListMessageBusesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_channel_connection(resp) + resp = self._interceptor.post_list_message_buses(resp) return resp - class _GetGoogleChannelConfig( - _BaseEventarcRestTransport._BaseGetGoogleChannelConfig, EventarcRestStub + class _ListPipelines( + _BaseEventarcRestTransport._BaseListPipelines, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.GetGoogleChannelConfig") + return hash("EventarcRestTransport.ListPipelines") @staticmethod def _get_response( @@ -1769,54 +4429,50 @@ def _get_response( def __call__( self, - request: eventarc.GetGoogleChannelConfigRequest, + request: eventarc.ListPipelinesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> google_channel_config.GoogleChannelConfig: - r"""Call the get google channel config method over HTTP. + ) -> eventarc.ListPipelinesResponse: + r"""Call the list pipelines method over HTTP. Args: - request (~.eventarc.GetGoogleChannelConfigRequest): + request (~.eventarc.ListPipelinesRequest): The request object. The request message for the - GetGoogleChannelConfig method. + ListPipelines method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.google_channel_config.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. + sent along with the request as metadata. + + Returns: + ~.eventarc.ListPipelinesResponse: + The response message for the + ListPipelines method. """ http_options = ( - _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_http_options() + _BaseEventarcRestTransport._BaseListPipelines._get_http_options() ) - request, metadata = self._interceptor.pre_get_google_channel_config( - request, metadata - ) - transcoded_request = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_transcoded_request( - http_options, request + request, metadata = self._interceptor.pre_list_pipelines(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseListPipelines._get_transcoded_request( + http_options, request + ) ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_query_params_json( - transcoded_request + query_params = ( + _BaseEventarcRestTransport._BaseListPipelines._get_query_params_json( + transcoded_request + ) ) # Send the request - response = EventarcRestTransport._GetGoogleChannelConfig._get_response( + response = EventarcRestTransport._ListPipelines._get_response( self._host, metadata, query_params, @@ -1831,16 +4487,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = google_channel_config.GoogleChannelConfig() - pb_resp = google_channel_config.GoogleChannelConfig.pb(resp) + resp = eventarc.ListPipelinesResponse() + pb_resp = eventarc.ListPipelinesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_google_channel_config(resp) + resp = self._interceptor.post_list_pipelines(resp) return resp - class _GetProvider(_BaseEventarcRestTransport._BaseGetProvider, EventarcRestStub): + class _ListProviders( + _BaseEventarcRestTransport._BaseListProviders, EventarcRestStub + ): def __hash__(self): - return hash("EventarcRestTransport.GetProvider") + return hash("EventarcRestTransport.ListProviders") @staticmethod def _get_response( @@ -1866,18 +4524,18 @@ def _get_response( def __call__( self, - request: eventarc.GetProviderRequest, + request: eventarc.ListProvidersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> discovery.Provider: - r"""Call the get provider method over HTTP. + ) -> eventarc.ListProvidersResponse: + r"""Call the list providers method over HTTP. Args: - request (~.eventarc.GetProviderRequest): + request (~.eventarc.ListProvidersRequest): The request object. The request message for the - GetProvider method. + ListProviders method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1885,31 +4543,29 @@ def __call__( sent along with the request as metadata. Returns: - ~.discovery.Provider: - A representation of the Provider - resource. - + ~.eventarc.ListProvidersResponse: + The response message for the ``ListProviders`` method. """ http_options = ( - _BaseEventarcRestTransport._BaseGetProvider._get_http_options() + _BaseEventarcRestTransport._BaseListProviders._get_http_options() ) - request, metadata = self._interceptor.pre_get_provider(request, metadata) + request, metadata = self._interceptor.pre_list_providers(request, metadata) transcoded_request = ( - _BaseEventarcRestTransport._BaseGetProvider._get_transcoded_request( + _BaseEventarcRestTransport._BaseListProviders._get_transcoded_request( http_options, request ) ) # Jsonify the query params query_params = ( - _BaseEventarcRestTransport._BaseGetProvider._get_query_params_json( + _BaseEventarcRestTransport._BaseListProviders._get_query_params_json( transcoded_request ) ) # Send the request - response = EventarcRestTransport._GetProvider._get_response( + response = EventarcRestTransport._ListProviders._get_response( self._host, metadata, query_params, @@ -1924,16 +4580,16 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = discovery.Provider() - pb_resp = discovery.Provider.pb(resp) + resp = eventarc.ListProvidersResponse() + pb_resp = eventarc.ListProvidersResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_provider(resp) + resp = self._interceptor.post_list_providers(resp) return resp - class _GetTrigger(_BaseEventarcRestTransport._BaseGetTrigger, EventarcRestStub): + class _ListTriggers(_BaseEventarcRestTransport._BaseListTriggers, EventarcRestStub): def __hash__(self): - return hash("EventarcRestTransport.GetTrigger") + return hash("EventarcRestTransport.ListTriggers") @staticmethod def _get_response( @@ -1959,18 +4615,18 @@ def _get_response( def __call__( self, - request: eventarc.GetTriggerRequest, + request: eventarc.ListTriggersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> trigger.Trigger: - r"""Call the get trigger method over HTTP. + ) -> eventarc.ListTriggersResponse: + r"""Call the list triggers method over HTTP. Args: - request (~.eventarc.GetTriggerRequest): + request (~.eventarc.ListTriggersRequest): The request object. The request message for the - GetTrigger method. + ListTriggers method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1978,31 +4634,29 @@ def __call__( sent along with the request as metadata. Returns: - ~.trigger.Trigger: - A representation of the trigger - resource. - + ~.eventarc.ListTriggersResponse: + The response message for the ``ListTriggers`` method. """ http_options = ( - _BaseEventarcRestTransport._BaseGetTrigger._get_http_options() + _BaseEventarcRestTransport._BaseListTriggers._get_http_options() ) - request, metadata = self._interceptor.pre_get_trigger(request, metadata) + request, metadata = self._interceptor.pre_list_triggers(request, metadata) transcoded_request = ( - _BaseEventarcRestTransport._BaseGetTrigger._get_transcoded_request( + _BaseEventarcRestTransport._BaseListTriggers._get_transcoded_request( http_options, request ) ) # Jsonify the query params query_params = ( - _BaseEventarcRestTransport._BaseGetTrigger._get_query_params_json( + _BaseEventarcRestTransport._BaseListTriggers._get_query_params_json( transcoded_request ) ) # Send the request - response = EventarcRestTransport._GetTrigger._get_response( + response = EventarcRestTransport._ListTriggers._get_response( self._host, metadata, query_params, @@ -2017,18 +4671,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = trigger.Trigger() - pb_resp = trigger.Trigger.pb(resp) + resp = eventarc.ListTriggersResponse() + pb_resp = eventarc.ListTriggersResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_trigger(resp) + resp = self._interceptor.post_list_triggers(resp) return resp - class _ListChannelConnections( - _BaseEventarcRestTransport._BaseListChannelConnections, EventarcRestStub + class _UpdateChannel( + _BaseEventarcRestTransport._BaseUpdateChannel, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.ListChannelConnections") + return hash("EventarcRestTransport.UpdateChannel") @staticmethod def _get_response( @@ -2049,23 +4703,24 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: eventarc.ListChannelConnectionsRequest, + request: eventarc.UpdateChannelRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> eventarc.ListChannelConnectionsResponse: - r"""Call the list channel connections method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update channel method over HTTP. Args: - request (~.eventarc.ListChannelConnectionsRequest): + request (~.eventarc.UpdateChannelRequest): The request object. The request message for the - ListChannelConnections method. + UpdateChannel method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2073,35 +4728,43 @@ def __call__( sent along with the request as metadata. Returns: - ~.eventarc.ListChannelConnectionsResponse: - The response message for the ``ListChannelConnections`` - method. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseEventarcRestTransport._BaseListChannelConnections._get_http_options() + _BaseEventarcRestTransport._BaseUpdateChannel._get_http_options() ) - request, metadata = self._interceptor.pre_list_channel_connections( - request, metadata + request, metadata = self._interceptor.pre_update_channel(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseUpdateChannel._get_transcoded_request( + http_options, request + ) ) - transcoded_request = _BaseEventarcRestTransport._BaseListChannelConnections._get_transcoded_request( - http_options, request + + body = _BaseEventarcRestTransport._BaseUpdateChannel._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseListChannelConnections._get_query_params_json( - transcoded_request + query_params = ( + _BaseEventarcRestTransport._BaseUpdateChannel._get_query_params_json( + transcoded_request + ) ) # Send the request - response = EventarcRestTransport._ListChannelConnections._get_response( + response = EventarcRestTransport._UpdateChannel._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2110,16 +4773,16 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = eventarc.ListChannelConnectionsResponse() - pb_resp = eventarc.ListChannelConnectionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_channel_connections(resp) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_channel(resp) return resp - class _ListChannels(_BaseEventarcRestTransport._BaseListChannels, EventarcRestStub): + class _UpdateEnrollment( + _BaseEventarcRestTransport._BaseUpdateEnrollment, EventarcRestStub + ): def __hash__(self): - return hash("EventarcRestTransport.ListChannels") + return hash("EventarcRestTransport.UpdateEnrollment") @staticmethod def _get_response( @@ -2140,23 +4803,24 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: eventarc.ListChannelsRequest, + request: eventarc.UpdateEnrollmentRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> eventarc.ListChannelsResponse: - r"""Call the list channels method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update enrollment method over HTTP. Args: - request (~.eventarc.ListChannelsRequest): + request (~.eventarc.UpdateEnrollmentRequest): The request object. The request message for the - ListChannels method. + UpdateEnrollment method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2164,35 +4828,45 @@ def __call__( sent along with the request as metadata. Returns: - ~.eventarc.ListChannelsResponse: - The response message for the ``ListChannels`` method. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + """ http_options = ( - _BaseEventarcRestTransport._BaseListChannels._get_http_options() + _BaseEventarcRestTransport._BaseUpdateEnrollment._get_http_options() ) - request, metadata = self._interceptor.pre_list_channels(request, metadata) - transcoded_request = ( - _BaseEventarcRestTransport._BaseListChannels._get_transcoded_request( - http_options, request + request, metadata = self._interceptor.pre_update_enrollment( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateEnrollment._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseEventarcRestTransport._BaseUpdateEnrollment._get_request_body_json( + transcoded_request ) ) # Jsonify the query params query_params = ( - _BaseEventarcRestTransport._BaseListChannels._get_query_params_json( + _BaseEventarcRestTransport._BaseUpdateEnrollment._get_query_params_json( transcoded_request ) ) # Send the request - response = EventarcRestTransport._ListChannels._get_response( + response = EventarcRestTransport._UpdateEnrollment._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2201,18 +4875,16 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = eventarc.ListChannelsResponse() - pb_resp = eventarc.ListChannelsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_channels(resp) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_enrollment(resp) return resp - class _ListProviders( - _BaseEventarcRestTransport._BaseListProviders, EventarcRestStub + class _UpdateGoogleApiSource( + _BaseEventarcRestTransport._BaseUpdateGoogleApiSource, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.ListProviders") + return hash("EventarcRestTransport.UpdateGoogleApiSource") @staticmethod def _get_response( @@ -2233,23 +4905,24 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: eventarc.ListProvidersRequest, + request: eventarc.UpdateGoogleApiSourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> eventarc.ListProvidersResponse: - r"""Call the list providers method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update google api source method over HTTP. Args: - request (~.eventarc.ListProvidersRequest): + request (~.eventarc.UpdateGoogleApiSourceRequest): The request object. The request message for the - ListProviders method. + UpdateGoogleApiSource method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2257,35 +4930,41 @@ def __call__( sent along with the request as metadata. Returns: - ~.eventarc.ListProvidersResponse: - The response message for the ``ListProviders`` method. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + """ http_options = ( - _BaseEventarcRestTransport._BaseListProviders._get_http_options() + _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_http_options() ) - request, metadata = self._interceptor.pre_list_providers(request, metadata) - transcoded_request = ( - _BaseEventarcRestTransport._BaseListProviders._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_update_google_api_source( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_transcoded_request( + http_options, request + ) + + body = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = ( - _BaseEventarcRestTransport._BaseListProviders._get_query_params_json( - transcoded_request - ) + query_params = _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_query_params_json( + transcoded_request ) # Send the request - response = EventarcRestTransport._ListProviders._get_response( + response = EventarcRestTransport._UpdateGoogleApiSource._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2294,16 +4973,16 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = eventarc.ListProvidersResponse() - pb_resp = eventarc.ListProvidersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_providers(resp) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_google_api_source(resp) return resp - class _ListTriggers(_BaseEventarcRestTransport._BaseListTriggers, EventarcRestStub): + class _UpdateGoogleChannelConfig( + _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig, EventarcRestStub + ): def __hash__(self): - return hash("EventarcRestTransport.ListTriggers") + return hash("EventarcRestTransport.UpdateGoogleChannelConfig") @staticmethod def _get_response( @@ -2324,59 +5003,72 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: eventarc.ListTriggersRequest, + request: eventarc.UpdateGoogleChannelConfigRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> eventarc.ListTriggersResponse: - r"""Call the list triggers method over HTTP. + ) -> gce_google_channel_config.GoogleChannelConfig: + r"""Call the update google channel + config method over HTTP. + + Args: + request (~.eventarc.UpdateGoogleChannelConfigRequest): + The request object. The request message for the + UpdateGoogleChannelConfig method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. - Args: - request (~.eventarc.ListTriggersRequest): - The request object. The request message for the - ListTriggers method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + Returns: + ~.gce_google_channel_config.GoogleChannelConfig: + A GoogleChannelConfig is a resource + that stores the custom settings + respected by Eventarc first-party + triggers in the matching region. Once + configured, first-party event data will + be protected using the specified custom + managed encryption key instead of + Google-managed encryption keys. - Returns: - ~.eventarc.ListTriggersResponse: - The response message for the ``ListTriggers`` method. """ http_options = ( - _BaseEventarcRestTransport._BaseListTriggers._get_http_options() + _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_http_options() ) - request, metadata = self._interceptor.pre_list_triggers(request, metadata) - transcoded_request = ( - _BaseEventarcRestTransport._BaseListTriggers._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_update_google_channel_config( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = ( - _BaseEventarcRestTransport._BaseListTriggers._get_query_params_json( - transcoded_request - ) + query_params = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_query_params_json( + transcoded_request ) # Send the request - response = EventarcRestTransport._ListTriggers._get_response( + response = EventarcRestTransport._UpdateGoogleChannelConfig._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2385,18 +5077,18 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = eventarc.ListTriggersResponse() - pb_resp = eventarc.ListTriggersResponse.pb(resp) + resp = gce_google_channel_config.GoogleChannelConfig() + pb_resp = gce_google_channel_config.GoogleChannelConfig.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_triggers(resp) + resp = self._interceptor.post_update_google_channel_config(resp) return resp - class _UpdateChannel( - _BaseEventarcRestTransport._BaseUpdateChannel, EventarcRestStub + class _UpdateMessageBus( + _BaseEventarcRestTransport._BaseUpdateMessageBus, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.UpdateChannel") + return hash("EventarcRestTransport.UpdateMessageBus") @staticmethod def _get_response( @@ -2423,18 +5115,18 @@ def _get_response( def __call__( self, - request: eventarc.UpdateChannelRequest, + request: eventarc.UpdateMessageBusRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operations_pb2.Operation: - r"""Call the update channel method over HTTP. + r"""Call the update message bus method over HTTP. Args: - request (~.eventarc.UpdateChannelRequest): + request (~.eventarc.UpdateMessageBusRequest): The request object. The request message for the - UpdateChannel method. + UpdateMessageBus method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2450,28 +5142,30 @@ def __call__( """ http_options = ( - _BaseEventarcRestTransport._BaseUpdateChannel._get_http_options() + _BaseEventarcRestTransport._BaseUpdateMessageBus._get_http_options() ) - request, metadata = self._interceptor.pre_update_channel(request, metadata) - transcoded_request = ( - _BaseEventarcRestTransport._BaseUpdateChannel._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_update_message_bus( + request, metadata + ) + transcoded_request = _BaseEventarcRestTransport._BaseUpdateMessageBus._get_transcoded_request( + http_options, request ) - body = _BaseEventarcRestTransport._BaseUpdateChannel._get_request_body_json( - transcoded_request + body = ( + _BaseEventarcRestTransport._BaseUpdateMessageBus._get_request_body_json( + transcoded_request + ) ) # Jsonify the query params query_params = ( - _BaseEventarcRestTransport._BaseUpdateChannel._get_query_params_json( + _BaseEventarcRestTransport._BaseUpdateMessageBus._get_query_params_json( transcoded_request ) ) # Send the request - response = EventarcRestTransport._UpdateChannel._get_response( + response = EventarcRestTransport._UpdateMessageBus._get_response( self._host, metadata, query_params, @@ -2489,14 +5183,14 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_channel(resp) + resp = self._interceptor.post_update_message_bus(resp) return resp - class _UpdateGoogleChannelConfig( - _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig, EventarcRestStub + class _UpdatePipeline( + _BaseEventarcRestTransport._BaseUpdatePipeline, EventarcRestStub ): def __hash__(self): - return hash("EventarcRestTransport.UpdateGoogleChannelConfig") + return hash("EventarcRestTransport.UpdatePipeline") @staticmethod def _get_response( @@ -2523,59 +5217,57 @@ def _get_response( def __call__( self, - request: eventarc.UpdateGoogleChannelConfigRequest, + request: eventarc.UpdatePipelineRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> gce_google_channel_config.GoogleChannelConfig: - r"""Call the update google channel - config method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update pipeline method over HTTP. - Args: - request (~.eventarc.UpdateGoogleChannelConfigRequest): - The request object. The request message for the - UpdateGoogleChannelConfig method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + Args: + request (~.eventarc.UpdatePipelineRequest): + The request object. The request message for the + UpdatePipeline method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. - Returns: - ~.gce_google_channel_config.GoogleChannelConfig: - A GoogleChannelConfig is a resource - that stores the custom settings - respected by Eventarc first-party - triggers in the matching region. Once - configured, first-party event data will - be protected using the specified custom - managed encryption key instead of - Google-managed encryption keys. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_http_options() - ) - request, metadata = self._interceptor.pre_update_google_channel_config( - request, metadata + _BaseEventarcRestTransport._BaseUpdatePipeline._get_http_options() ) - transcoded_request = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_transcoded_request( - http_options, request + request, metadata = self._interceptor.pre_update_pipeline(request, metadata) + transcoded_request = ( + _BaseEventarcRestTransport._BaseUpdatePipeline._get_transcoded_request( + http_options, request + ) ) - body = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_request_body_json( - transcoded_request + body = ( + _BaseEventarcRestTransport._BaseUpdatePipeline._get_request_body_json( + transcoded_request + ) ) # Jsonify the query params - query_params = _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_query_params_json( - transcoded_request + query_params = ( + _BaseEventarcRestTransport._BaseUpdatePipeline._get_query_params_json( + transcoded_request + ) ) # Send the request - response = EventarcRestTransport._UpdateGoogleChannelConfig._get_response( + response = EventarcRestTransport._UpdatePipeline._get_response( self._host, metadata, query_params, @@ -2591,11 +5283,9 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = gce_google_channel_config.GoogleChannelConfig() - pb_resp = gce_google_channel_config.GoogleChannelConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_google_channel_config(resp) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_pipeline(resp) return resp class _UpdateTrigger( @@ -2714,6 +5404,38 @@ def create_channel_connection( # In C++ this would require a dynamic_cast return self._CreateChannelConnection(self._session, self._host, self._interceptor) # type: ignore + @property + def create_enrollment( + self, + ) -> Callable[[eventarc.CreateEnrollmentRequest], operations_pb2.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._CreateEnrollment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_google_api_source( + self, + ) -> Callable[[eventarc.CreateGoogleApiSourceRequest], operations_pb2.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._CreateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_message_bus( + self, + ) -> Callable[[eventarc.CreateMessageBusRequest], operations_pb2.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._CreateMessageBus(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_pipeline( + self, + ) -> Callable[[eventarc.CreatePipelineRequest], operations_pb2.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._CreatePipeline(self._session, self._host, self._interceptor) # type: ignore + @property def create_trigger( self, @@ -2738,6 +5460,38 @@ def delete_channel_connection( # In C++ this would require a dynamic_cast return self._DeleteChannelConnection(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_enrollment( + self, + ) -> Callable[[eventarc.DeleteEnrollmentRequest], operations_pb2.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._DeleteEnrollment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_google_api_source( + self, + ) -> Callable[[eventarc.DeleteGoogleApiSourceRequest], operations_pb2.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._DeleteGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_message_bus( + self, + ) -> Callable[[eventarc.DeleteMessageBusRequest], operations_pb2.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._DeleteMessageBus(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_pipeline( + self, + ) -> Callable[[eventarc.DeletePipelineRequest], operations_pb2.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._DeletePipeline(self._session, self._host, self._interceptor) # type: ignore + @property def delete_trigger( self, @@ -2762,6 +5516,24 @@ def get_channel_connection( # In C++ this would require a dynamic_cast return self._GetChannelConnection(self._session, self._host, self._interceptor) # type: ignore + @property + def get_enrollment( + self, + ) -> Callable[[eventarc.GetEnrollmentRequest], enrollment.Enrollment]: + # 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._GetEnrollment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_google_api_source( + self, + ) -> Callable[ + [eventarc.GetGoogleApiSourceRequest], google_api_source.GoogleApiSource + ]: + # 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._GetGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + @property def get_google_channel_config( self, @@ -2773,6 +5545,22 @@ def get_google_channel_config( # In C++ this would require a dynamic_cast return self._GetGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore + @property + def get_message_bus( + self, + ) -> Callable[[eventarc.GetMessageBusRequest], message_bus.MessageBus]: + # 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._GetMessageBus(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_pipeline( + self, + ) -> Callable[[eventarc.GetPipelineRequest], pipeline.Pipeline]: + # 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._GetPipeline(self._session, self._host, self._interceptor) # type: ignore + @property def get_provider( self, @@ -2806,6 +5594,53 @@ def list_channels( # In C++ this would require a dynamic_cast return self._ListChannels(self._session, self._host, self._interceptor) # type: ignore + @property + def list_enrollments( + self, + ) -> Callable[[eventarc.ListEnrollmentsRequest], eventarc.ListEnrollmentsResponse]: + # 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._ListEnrollments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_google_api_sources( + self, + ) -> Callable[ + [eventarc.ListGoogleApiSourcesRequest], eventarc.ListGoogleApiSourcesResponse + ]: + # 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._ListGoogleApiSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_message_bus_enrollments( + self, + ) -> Callable[ + [eventarc.ListMessageBusEnrollmentsRequest], + eventarc.ListMessageBusEnrollmentsResponse, + ]: + # 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._ListMessageBusEnrollments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_message_buses( + self, + ) -> Callable[ + [eventarc.ListMessageBusesRequest], eventarc.ListMessageBusesResponse + ]: + # 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._ListMessageBuses(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_pipelines( + self, + ) -> Callable[[eventarc.ListPipelinesRequest], eventarc.ListPipelinesResponse]: + # 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._ListPipelines(self._session, self._host, self._interceptor) # type: ignore + @property def list_providers( self, @@ -2830,6 +5665,22 @@ def update_channel( # In C++ this would require a dynamic_cast return self._UpdateChannel(self._session, self._host, self._interceptor) # type: ignore + @property + def update_enrollment( + self, + ) -> Callable[[eventarc.UpdateEnrollmentRequest], operations_pb2.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._UpdateEnrollment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_google_api_source( + self, + ) -> Callable[[eventarc.UpdateGoogleApiSourceRequest], operations_pb2.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._UpdateGoogleApiSource(self._session, self._host, self._interceptor) # type: ignore + @property def update_google_channel_config( self, @@ -2841,6 +5692,22 @@ def update_google_channel_config( # In C++ this would require a dynamic_cast return self._UpdateGoogleChannelConfig(self._session, self._host, self._interceptor) # type: ignore + @property + def update_message_bus( + self, + ) -> Callable[[eventarc.UpdateMessageBusRequest], operations_pb2.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._UpdateMessageBus(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_pipeline( + self, + ) -> Callable[[eventarc.UpdatePipelineRequest], operations_pb2.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._UpdatePipeline(self._session, self._host, self._interceptor) # type: ignore + @property def update_trigger( self, diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py index 1fd1045d09a6..28715f6327c6 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/services/eventarc/transports/rest_base.py @@ -28,13 +28,15 @@ channel, channel_connection, discovery, + enrollment, eventarc, + google_api_source, ) from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import google_channel_config -from google.cloud.eventarc_v1.types import trigger +from google.cloud.eventarc_v1.types import message_bus, pipeline, trigger from .base import DEFAULT_CLIENT_INFO, EventarcTransport @@ -107,7 +109,6 @@ def __hash__(self): # pragma: NO COVER __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { "channelId": "", - "validateOnly": False, } @classmethod @@ -220,14 +221,1011 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCreateEnrollment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "enrollmentId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/enrollments", + "body": "enrollment", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateEnrollmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseCreateEnrollment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateGoogleApiSource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "googleApiSourceId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/googleApiSources", + "body": "google_api_source", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateGoogleApiSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseCreateGoogleApiSource._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateMessageBus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "messageBusId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/messageBuses", + "body": "message_bus", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateMessageBusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseCreateMessageBus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreatePipeline: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "pipelineId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/pipelines", + "body": "pipeline", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreatePipelineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseCreatePipeline._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCreateTrigger: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "triggerId": "", - "validateOnly": False, - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "triggerId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/triggers", + "body": "trigger", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.CreateTriggerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseCreateTrigger._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteChannel: + 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": "/v1/{name=projects/*/locations/*/channels/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteChannelRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseDeleteChannel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteChannelConnection: + 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": "/v1/{name=projects/*/locations/*/channelConnections/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteChannelConnectionRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEnrollment: + 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": "/v1/{name=projects/*/locations/*/enrollments/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteEnrollmentRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseDeleteEnrollment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteGoogleApiSource: + 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": "/v1/{name=projects/*/locations/*/googleApiSources/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteGoogleApiSourceRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseDeleteGoogleApiSource._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMessageBus: + 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": "/v1/{name=projects/*/locations/*/messageBuses/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteMessageBusRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseDeleteMessageBus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePipeline: + 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": "/v1/{name=projects/*/locations/*/pipelines/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeletePipelineRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseDeletePipeline._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTrigger: + 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": "/v1/{name=projects/*/locations/*/triggers/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.DeleteTriggerRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseDeleteTrigger._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetChannel: + 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": "/v1/{name=projects/*/locations/*/channels/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetChannelRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseGetChannel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetChannelConnection: + 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": "/v1/{name=projects/*/locations/*/channelConnections/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetChannelConnectionRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseGetChannelConnection._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEnrollment: + 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": "/v1/{name=projects/*/locations/*/enrollments/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetEnrollmentRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseGetEnrollment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGoogleApiSource: + 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": "/v1/{name=projects/*/locations/*/googleApiSources/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetGoogleApiSourceRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseGetGoogleApiSource._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGoogleChannelConfig: + 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": "/v1/{name=projects/*/locations/*/googleChannelConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetGoogleChannelConfigRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetMessageBus: + 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": "/v1/{name=projects/*/locations/*/messageBuses/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetMessageBusRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseGetMessageBus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPipeline: + 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": "/v1/{name=projects/*/locations/*/pipelines/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetPipelineRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseGetPipeline._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProvider: + 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": "/v1/{name=projects/*/locations/*/providers/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.GetProviderRequest.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=True, + ) + ) + query_params.update( + _BaseEventarcRestTransport._BaseGetProvider._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTrigger: + 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): @@ -241,28 +1239,18 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/triggers", - "body": "trigger", + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/triggers/*}", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.CreateTriggerRequest.pb(request) + pb_request = eventarc.GetTriggerRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - return body - @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -272,7 +1260,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseCreateTrigger._get_unset_required_fields( + _BaseEventarcRestTransport._BaseGetTrigger._get_unset_required_fields( query_params ) ) @@ -280,13 +1268,11 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseDeleteChannel: + class _BaseListChannelConnections: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "validateOnly": False, - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -300,15 +1286,15 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/channels/*}", + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/channelConnections", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteChannelRequest.pb(request) + pb_request = eventarc.ListChannelConnectionsRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -321,7 +1307,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseDeleteChannel._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListChannelConnections._get_unset_required_fields( query_params ) ) @@ -329,7 +1315,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseDeleteChannelConnection: + class _BaseListChannels: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -347,15 +1333,15 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/channelConnections/*}", + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/channels", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteChannelConnectionRequest.pb(request) + pb_request = eventarc.ListChannelsRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -368,7 +1354,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseDeleteChannelConnection._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListChannels._get_unset_required_fields( query_params ) ) @@ -376,13 +1362,11 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseDeleteTrigger: + class _BaseListEnrollments: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "validateOnly": False, - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -396,15 +1380,15 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/triggers/*}", + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/enrollments", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.DeleteTriggerRequest.pb(request) + pb_request = eventarc.ListEnrollmentsRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -417,7 +1401,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseDeleteTrigger._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListEnrollments._get_unset_required_fields( query_params ) ) @@ -425,7 +1409,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetChannel: + class _BaseListGoogleApiSources: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -444,14 +1428,14 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "get", - "uri": "/v1/{name=projects/*/locations/*/channels/*}", + "uri": "/v1/{parent=projects/*/locations/*}/googleApiSources", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetChannelRequest.pb(request) + pb_request = eventarc.ListGoogleApiSourcesRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -464,7 +1448,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseGetChannel._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListGoogleApiSources._get_unset_required_fields( query_params ) ) @@ -472,7 +1456,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetChannelConnection: + class _BaseListMessageBusEnrollments: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -491,14 +1475,14 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "get", - "uri": "/v1/{name=projects/*/locations/*/channelConnections/*}", + "uri": "/v1/{parent=projects/*/locations/*/messageBuses/*}:listEnrollments", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetChannelConnectionRequest.pb(request) + pb_request = eventarc.ListMessageBusEnrollmentsRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -511,7 +1495,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseGetChannelConnection._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListMessageBusEnrollments._get_unset_required_fields( query_params ) ) @@ -519,7 +1503,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetGoogleChannelConfig: + class _BaseListMessageBuses: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -538,14 +1522,14 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "get", - "uri": "/v1/{name=projects/*/locations/*/googleChannelConfig}", + "uri": "/v1/{parent=projects/*/locations/*}/messageBuses", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetGoogleChannelConfigRequest.pb(request) + pb_request = eventarc.ListMessageBusesRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -558,7 +1542,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseGetGoogleChannelConfig._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListMessageBuses._get_unset_required_fields( query_params ) ) @@ -566,7 +1550,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetProvider: + class _BaseListPipelines: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -585,14 +1569,14 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "get", - "uri": "/v1/{name=projects/*/locations/*/providers/*}", + "uri": "/v1/{parent=projects/*/locations/*}/pipelines", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetProviderRequest.pb(request) + pb_request = eventarc.ListPipelinesRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -605,7 +1589,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseGetProvider._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListPipelines._get_unset_required_fields( query_params ) ) @@ -613,7 +1597,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetTrigger: + class _BaseListProviders: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -632,14 +1616,14 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "get", - "uri": "/v1/{name=projects/*/locations/*/triggers/*}", + "uri": "/v1/{parent=projects/*/locations/*}/providers", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.GetTriggerRequest.pb(request) + pb_request = eventarc.ListProvidersRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -652,7 +1636,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseGetTrigger._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListProviders._get_unset_required_fields( query_params ) ) @@ -660,7 +1644,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseListChannelConnections: + class _BaseListTriggers: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -679,14 +1663,14 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/channelConnections", + "uri": "/v1/{parent=projects/*/locations/*}/triggers", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListChannelConnectionsRequest.pb(request) + pb_request = eventarc.ListTriggersRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -699,7 +1683,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseListChannelConnections._get_unset_required_fields( + _BaseEventarcRestTransport._BaseListTriggers._get_unset_required_fields( query_params ) ) @@ -707,7 +1691,49 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseListChannels: + class _BaseUpdateChannel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{channel.name=projects/*/locations/*/channels/*}", + "body": "channel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = eventarc.UpdateChannelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEnrollment: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -725,18 +1751,28 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/channels", + "method": "patch", + "uri": "/v1/{enrollment.name=projects/*/locations/*/enrollments/*}", + "body": "enrollment", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListChannelsRequest.pb(request) + pb_request = eventarc.UpdateEnrollmentRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -746,7 +1782,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseListChannels._get_unset_required_fields( + _BaseEventarcRestTransport._BaseUpdateEnrollment._get_unset_required_fields( query_params ) ) @@ -754,7 +1790,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseListProviders: + class _BaseUpdateGoogleApiSource: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -772,18 +1808,28 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/providers", + "method": "patch", + "uri": "/v1/{google_api_source.name=projects/*/locations/*/googleApiSources/*}", + "body": "google_api_source", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListProvidersRequest.pb(request) + pb_request = eventarc.UpdateGoogleApiSourceRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -793,7 +1839,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseListProviders._get_unset_required_fields( + _BaseEventarcRestTransport._BaseUpdateGoogleApiSource._get_unset_required_fields( query_params ) ) @@ -801,7 +1847,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseListTriggers: + class _BaseUpdateGoogleChannelConfig: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -819,18 +1865,28 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/triggers", + "method": "patch", + "uri": "/v1/{google_channel_config.name=projects/*/locations/*/googleChannelConfig}", + "body": "google_channel_config", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.ListTriggersRequest.pb(request) + pb_request = eventarc.UpdateGoogleChannelConfigRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -840,7 +1896,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseListTriggers._get_unset_required_fields( + _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_unset_required_fields( query_params ) ) @@ -848,13 +1904,11 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseUpdateChannel: + class _BaseUpdateMessageBus: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "validateOnly": False, - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -869,15 +1923,15 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "patch", - "uri": "/v1/{channel.name=projects/*/locations/*/channels/*}", - "body": "channel", + "uri": "/v1/{message_bus.name=projects/*/locations/*/messageBuses/*}", + "body": "message_bus", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdateChannelRequest.pb(request) + pb_request = eventarc.UpdateMessageBusRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -899,7 +1953,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseUpdateChannel._get_unset_required_fields( + _BaseEventarcRestTransport._BaseUpdateMessageBus._get_unset_required_fields( query_params ) ) @@ -907,7 +1961,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseUpdateGoogleChannelConfig: + class _BaseUpdatePipeline: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -926,15 +1980,15 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "patch", - "uri": "/v1/{google_channel_config.name=projects/*/locations/*/googleChannelConfig}", - "body": "google_channel_config", + "uri": "/v1/{pipeline.name=projects/*/locations/*/pipelines/*}", + "body": "pipeline", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = eventarc.UpdateGoogleChannelConfigRequest.pb(request) + pb_request = eventarc.UpdatePipelineRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -956,7 +2010,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseEventarcRestTransport._BaseUpdateGoogleChannelConfig._get_unset_required_fields( + _BaseEventarcRestTransport._BaseUpdatePipeline._get_unset_required_fields( query_params ) ) @@ -968,18 +2022,6 @@ class _BaseUpdateTrigger: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "validateOnly": False, - } - - @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]] = [ @@ -1014,11 +2056,6 @@ def _get_query_params_json(transcoded_request): use_integers_for_enums=True, ) ) - query_params.update( - _BaseEventarcRestTransport._BaseUpdateTrigger._get_unset_required_fields( - query_params - ) - ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -1092,6 +2129,22 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/channelConnections/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/messageBuses/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/enrollments/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/pipelines/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/googleApiSources/*}:getIamPolicy", + }, ] return http_options @@ -1128,6 +2181,26 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/channelConnections/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/messageBuses/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/enrollments/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/pipelines/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/googleApiSources/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -1169,6 +2242,26 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/channelConnections/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/messageBuses/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/enrollments/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/pipelines/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/googleApiSources/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/__init__.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/__init__.py index f3ff2cbf960f..4d989cfaa460 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/__init__.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/__init__.py @@ -16,37 +16,70 @@ from .channel import Channel from .channel_connection import ChannelConnection from .discovery import EventType, FilteringAttribute, Provider +from .enrollment import Enrollment from .eventarc import ( CreateChannelConnectionRequest, CreateChannelRequest, + CreateEnrollmentRequest, + CreateGoogleApiSourceRequest, + CreateMessageBusRequest, + CreatePipelineRequest, CreateTriggerRequest, DeleteChannelConnectionRequest, DeleteChannelRequest, + DeleteEnrollmentRequest, + DeleteGoogleApiSourceRequest, + DeleteMessageBusRequest, + DeletePipelineRequest, DeleteTriggerRequest, GetChannelConnectionRequest, GetChannelRequest, + GetEnrollmentRequest, + GetGoogleApiSourceRequest, GetGoogleChannelConfigRequest, + GetMessageBusRequest, + GetPipelineRequest, GetProviderRequest, GetTriggerRequest, ListChannelConnectionsRequest, ListChannelConnectionsResponse, ListChannelsRequest, ListChannelsResponse, + ListEnrollmentsRequest, + ListEnrollmentsResponse, + ListGoogleApiSourcesRequest, + ListGoogleApiSourcesResponse, + ListMessageBusEnrollmentsRequest, + ListMessageBusEnrollmentsResponse, + ListMessageBusesRequest, + ListMessageBusesResponse, + ListPipelinesRequest, + ListPipelinesResponse, ListProvidersRequest, ListProvidersResponse, ListTriggersRequest, ListTriggersResponse, OperationMetadata, UpdateChannelRequest, + UpdateEnrollmentRequest, + UpdateGoogleApiSourceRequest, UpdateGoogleChannelConfigRequest, + UpdateMessageBusRequest, + UpdatePipelineRequest, UpdateTriggerRequest, ) +from .google_api_source import GoogleApiSource from .google_channel_config import GoogleChannelConfig +from .logging_config import LoggingConfig +from .message_bus import MessageBus +from .network_config import NetworkConfig +from .pipeline import Pipeline from .trigger import ( GKE, CloudRun, Destination, EventFilter, + HttpEndpoint, Pubsub, StateCondition, Transport, @@ -59,34 +92,67 @@ "EventType", "FilteringAttribute", "Provider", + "Enrollment", "CreateChannelConnectionRequest", "CreateChannelRequest", + "CreateEnrollmentRequest", + "CreateGoogleApiSourceRequest", + "CreateMessageBusRequest", + "CreatePipelineRequest", "CreateTriggerRequest", "DeleteChannelConnectionRequest", "DeleteChannelRequest", + "DeleteEnrollmentRequest", + "DeleteGoogleApiSourceRequest", + "DeleteMessageBusRequest", + "DeletePipelineRequest", "DeleteTriggerRequest", "GetChannelConnectionRequest", "GetChannelRequest", + "GetEnrollmentRequest", + "GetGoogleApiSourceRequest", "GetGoogleChannelConfigRequest", + "GetMessageBusRequest", + "GetPipelineRequest", "GetProviderRequest", "GetTriggerRequest", "ListChannelConnectionsRequest", "ListChannelConnectionsResponse", "ListChannelsRequest", "ListChannelsResponse", + "ListEnrollmentsRequest", + "ListEnrollmentsResponse", + "ListGoogleApiSourcesRequest", + "ListGoogleApiSourcesResponse", + "ListMessageBusEnrollmentsRequest", + "ListMessageBusEnrollmentsResponse", + "ListMessageBusesRequest", + "ListMessageBusesResponse", + "ListPipelinesRequest", + "ListPipelinesResponse", "ListProvidersRequest", "ListProvidersResponse", "ListTriggersRequest", "ListTriggersResponse", "OperationMetadata", "UpdateChannelRequest", + "UpdateEnrollmentRequest", + "UpdateGoogleApiSourceRequest", "UpdateGoogleChannelConfigRequest", + "UpdateMessageBusRequest", + "UpdatePipelineRequest", "UpdateTriggerRequest", + "GoogleApiSource", "GoogleChannelConfig", + "LoggingConfig", + "MessageBus", + "NetworkConfig", + "Pipeline", "CloudRun", "Destination", "EventFilter", "GKE", + "HttpEndpoint", "Pubsub", "StateCondition", "Transport", diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel.py index 05eedbafd8df..131b20d8bce7 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/channel.py @@ -71,11 +71,15 @@ class Channel(proto.Message): channel. The token must be used by the provider to register the channel for publishing. crypto_key_name (str): - Optional. Resource name of a KMS crypto key (managed by the - user) used to encrypt/decrypt their event data. + Resource name of a KMS crypto key (managed by the user) used + to encrypt/decrypt their event data. It must match the pattern ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + satisfies_pzs (bool): + Output only. Whether or not this Channel + satisfies the requirements of physical zone + separation """ class State(proto.Enum): @@ -154,6 +158,10 @@ class State(proto.Enum): proto.STRING, number=11, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=12, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/enrollment.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/enrollment.py new file mode 100644 index 000000000000..907a26595c61 --- /dev/null +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/enrollment.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.eventarc.v1", + manifest={ + "Enrollment", + }, +) + + +class Enrollment(proto.Message): + r"""An enrollment represents a subscription for messages on a + particular message bus. It defines a matching criteria for + messages on the bus and the subscriber endpoint where matched + messages should be delivered. + + Attributes: + name (str): + Identifier. Resource name of the form + projects/{project}/locations/{location}/enrollments/{enrollment} + uid (str): + Output only. Server assigned unique + identifier for the channel. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on update and delete requests + to ensure that the client has an up-to-date + value before proceeding. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + labels (MutableMapping[str, str]): + Optional. Resource labels. + annotations (MutableMapping[str, str]): + Optional. Resource annotations. + display_name (str): + Optional. Resource display name. + cel_match (str): + Required. A CEL expression identifying which + messages this enrollment applies to. + message_bus (str): + Required. Resource name of the message bus + identifying the source of the messages. It + matches the form + projects/{project}/locations/{location}/messageBuses/{messageBus}. + destination (str): + Required. Destination is the Pipeline that the Enrollment is + delivering to. It must point to the full resource name of a + Pipeline. Format: + "projects/{PROJECT_ID}/locations/{region}/pipelines/{PIPELINE_ID)". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + cel_match: str = proto.Field( + proto.STRING, + number=9, + ) + message_bus: str = proto.Field( + proto.STRING, + number=10, + ) + destination: str = proto.Field( + proto.STRING, + number=11, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/eventarc.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/eventarc.py index 326c773a1fa8..073e7465df6e 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/eventarc.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/eventarc.py @@ -22,11 +22,15 @@ import proto # type: ignore from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import channel as gce_channel from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import pipeline as gce_pipeline from google.cloud.eventarc_v1.types import trigger as gce_trigger __protobuf__ = proto.module( @@ -54,6 +58,32 @@ "DeleteChannelConnectionRequest", "UpdateGoogleChannelConfigRequest", "GetGoogleChannelConfigRequest", + "GetMessageBusRequest", + "ListMessageBusesRequest", + "ListMessageBusesResponse", + "ListMessageBusEnrollmentsRequest", + "ListMessageBusEnrollmentsResponse", + "CreateMessageBusRequest", + "UpdateMessageBusRequest", + "DeleteMessageBusRequest", + "GetEnrollmentRequest", + "ListEnrollmentsRequest", + "ListEnrollmentsResponse", + "CreateEnrollmentRequest", + "UpdateEnrollmentRequest", + "DeleteEnrollmentRequest", + "GetPipelineRequest", + "ListPipelinesRequest", + "ListPipelinesResponse", + "CreatePipelineRequest", + "UpdatePipelineRequest", + "DeletePipelineRequest", + "GetGoogleApiSourceRequest", + "ListGoogleApiSourcesRequest", + "ListGoogleApiSourcesResponse", + "CreateGoogleApiSourceRequest", + "UpdateGoogleApiSourceRequest", + "DeleteGoogleApiSourceRequest", "OperationMetadata", }, ) @@ -175,7 +205,7 @@ class CreateTriggerRequest(proto.Message): Required. The user-provided ID to be assigned to the trigger. validate_only (bool): - Required. If set, validate the request and + Optional. If set, validate the request and preview the review, but do not post it. """ @@ -214,7 +244,7 @@ class UpdateTriggerRequest(proto.Message): will be created. In this situation, ``update_mask`` is ignored. validate_only (bool): - Required. If set, validate the request and + Optional. If set, validate the request and preview the review, but do not post it. """ @@ -254,7 +284,7 @@ class DeleteTriggerRequest(proto.Message): the request will succeed but no action will be taken on the server. validate_only (bool): - Required. If set, validate the request and + Optional. If set, validate the request and preview the review, but do not post it. """ @@ -382,7 +412,7 @@ class CreateChannelRequest(proto.Message): Required. The user-provided ID to be assigned to the channel. validate_only (bool): - Required. If set, validate the request and + Optional. If set, validate the request and preview the review, but do not post it. """ @@ -417,7 +447,7 @@ class UpdateChannelRequest(proto.Message): fields in the request are updated. To update all fields, provide a field mask of "*". validate_only (bool): - Required. If set, validate the request and + Optional. If set, validate the request and preview the review, but do not post it. """ @@ -445,7 +475,7 @@ class DeleteChannelRequest(proto.Message): Required. The name of the channel to be deleted. validate_only (bool): - Required. If set, validate the request and + Optional. If set, validate the request and preview the review, but do not post it. """ @@ -726,6 +756,935 @@ class GetGoogleChannelConfigRequest(proto.Message): ) +class GetMessageBusRequest(proto.Message): + r"""The request message for the GetMessageBus method. + + Attributes: + name (str): + Required. The name of the message bus to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMessageBusesRequest(proto.Message): + r"""The request message for the ListMessageBuses method. + + Attributes: + parent (str): + Required. The parent collection to list + triggers on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + order_by (str): + Optional. The sorting order of the resources returned. Value + should be a comma-separated list of fields. The default + sorting order is ascending. To specify descending order for + a field, append a ``desc`` suffix; for example: + ``name desc, update_time``. + filter (str): + Optional. The filter field that the list + request will filter on. Possible filtersare + described in https://google.aip.dev/160. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListMessageBusesResponse(proto.Message): + r"""The response message for the ``ListMessageBuses`` method. + + Attributes: + message_buses (MutableSequence[google.cloud.eventarc_v1.types.MessageBus]): + The requested message buses, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListMessageBuses`` to + request the next page. If this is empty, then there are no + more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + message_buses: MutableSequence[gce_message_bus.MessageBus] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_message_bus.MessageBus, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListMessageBusEnrollmentsRequest(proto.Message): + r"""The request message for the ``ListMessageBusEnrollments`` method. + + Attributes: + parent (str): + Required. The parent message bus to list + enrollments on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMessageBusEnrollmentsResponse(proto.Message): + r"""The response message for the ``ListMessageBusEnrollments`` method.\` + + Attributes: + enrollments (MutableSequence[str]): + The requested enrollments, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to + ``ListMessageBusEnrollments`` to request the next page. If + this is empty, then there are no more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + enrollments: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateMessageBusRequest(proto.Message): + r"""The request message for the CreateMessageBus method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this message bus. + message_bus (google.cloud.eventarc_v1.types.MessageBus): + Required. The message bus to create. + message_bus_id (str): + Required. The user-provided ID to be assigned to the + MessageBus. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$) + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + message_bus: gce_message_bus.MessageBus = proto.Field( + proto.MESSAGE, + number=2, + message=gce_message_bus.MessageBus, + ) + message_bus_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateMessageBusRequest(proto.Message): + r"""The request message for the UpdateMessageBus method. + + Attributes: + message_bus (google.cloud.eventarc_v1.types.MessageBus): + Required. The MessageBus to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update all + fields, provide a field mask of "*". + allow_missing (bool): + Optional. If set to true, and the MessageBus is not found, a + new MessageBus will be created. In this situation, + ``update_mask`` is ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + message_bus: gce_message_bus.MessageBus = proto.Field( + proto.MESSAGE, + number=1, + message=gce_message_bus.MessageBus, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteMessageBusRequest(proto.Message): + r"""The request message for the DeleteMessageBus method. + + Attributes: + name (str): + Required. The name of the MessageBus to be + deleted. + etag (str): + Optional. If provided, the MessageBus will + only be deleted if the etag matches the current + etag on the resource. + allow_missing (bool): + Optional. If set to true, and the MessageBus + is not found, the request will succeed but no + action will be taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetEnrollmentRequest(proto.Message): + r"""The request message for the GetEnrollment method. + + Attributes: + name (str): + Required. The name of the Enrollment to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEnrollmentsRequest(proto.Message): + r"""The request message for the ListEnrollments method. + + Attributes: + parent (str): + Required. The parent collection to list + triggers on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + order_by (str): + Optional. The sorting order of the resources returned. Value + should be a comma-separated list of fields. The default + sorting order is ascending. To specify descending order for + a field, append a ``desc`` suffix; for example: + ``name desc, update_time``. + filter (str): + Optional. The filter field that the list + request will filter on. Possible filtersare + described in https://google.aip.dev/160. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEnrollmentsResponse(proto.Message): + r"""The response message for the ``ListEnrollments`` method. + + Attributes: + enrollments (MutableSequence[google.cloud.eventarc_v1.types.Enrollment]): + The requested Enrollments, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListEnrollments`` to + request the next page. If this is empty, then there are no + more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + enrollments: MutableSequence[gce_enrollment.Enrollment] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_enrollment.Enrollment, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateEnrollmentRequest(proto.Message): + r"""The request message for the CreateEnrollment method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this enrollment. + enrollment (google.cloud.eventarc_v1.types.Enrollment): + Required. The enrollment to create. + enrollment_id (str): + Required. The user-provided ID to be assigned to the + Enrollment. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + enrollment: gce_enrollment.Enrollment = proto.Field( + proto.MESSAGE, + number=2, + message=gce_enrollment.Enrollment, + ) + enrollment_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateEnrollmentRequest(proto.Message): + r"""The request message for the UpdateEnrollment method. + + Attributes: + enrollment (google.cloud.eventarc_v1.types.Enrollment): + Required. The Enrollment to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update all + fields, provide a field mask of "*". + allow_missing (bool): + Optional. If set to true, and the Enrollment is not found, a + new Enrollment will be created. In this situation, + ``update_mask`` is ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + enrollment: gce_enrollment.Enrollment = proto.Field( + proto.MESSAGE, + number=1, + message=gce_enrollment.Enrollment, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteEnrollmentRequest(proto.Message): + r"""The request message for the DeleteEnrollment method. + + Attributes: + name (str): + Required. The name of the Enrollment to be + deleted. + etag (str): + Optional. If provided, the Enrollment will + only be deleted if the etag matches the current + etag on the resource. + allow_missing (bool): + Optional. If set to true, and the Enrollment + is not found, the request will succeed but no + action will be taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetPipelineRequest(proto.Message): + r"""The request message for the GetPipeline method. + + Attributes: + name (str): + Required. The name of the pipeline to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPipelinesRequest(proto.Message): + r"""The request message for the ListPipelines method. + + Attributes: + parent (str): + Required. The parent collection to list + pipelines on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + order_by (str): + Optional. The sorting order of the resources returned. Value + should be a comma-separated list of fields. The default + sorting order is ascending. To specify descending order for + a field, append a ``desc`` suffix; for example: + ``name desc, update_time``. + filter (str): + Optional. The filter field that the list + request will filter on. Possible filters are + described in https://google.aip.dev/160. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListPipelinesResponse(proto.Message): + r"""The response message for the ListPipelines method. + + Attributes: + pipelines (MutableSequence[google.cloud.eventarc_v1.types.Pipeline]): + The requested pipelines, up to the number specified in + ``page_size``. + next_page_token (str): + A page token that can be sent to ``ListPipelines`` to + request the next page. If this is empty, then there are no + more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + pipelines: MutableSequence[gce_pipeline.Pipeline] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_pipeline.Pipeline, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreatePipelineRequest(proto.Message): + r"""The request message for the CreatePipeline method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this pipeline. + pipeline (google.cloud.eventarc_v1.types.Pipeline): + Required. The pipeline to create. + pipeline_id (str): + Required. The user-provided ID to be assigned + to the Pipeline. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + pipeline: gce_pipeline.Pipeline = proto.Field( + proto.MESSAGE, + number=2, + message=gce_pipeline.Pipeline, + ) + pipeline_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdatePipelineRequest(proto.Message): + r"""The request message for the UpdatePipeline method. + + Attributes: + pipeline (google.cloud.eventarc_v1.types.Pipeline): + Required. The Pipeline to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update all + fields, provide a field mask of "*". + allow_missing (bool): + Optional. If set to true, and the Pipeline is not found, a + new Pipeline will be created. In this situation, + ``update_mask`` is ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + pipeline: gce_pipeline.Pipeline = proto.Field( + proto.MESSAGE, + number=1, + message=gce_pipeline.Pipeline, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeletePipelineRequest(proto.Message): + r"""The request message for the DeletePipeline method. + + Attributes: + name (str): + Required. The name of the Pipeline to be + deleted. + etag (str): + Optional. If provided, the Pipeline will only + be deleted if the etag matches the current etag + on the resource. + allow_missing (bool): + Optional. If set to true, and the Pipeline is + not found, the request will succeed but no + action will be taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetGoogleApiSourceRequest(proto.Message): + r"""The request message for the GetGoogleApiSource method. + + Attributes: + name (str): + Required. The name of the google api source + to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListGoogleApiSourcesRequest(proto.Message): + r"""The request message for the ListGoogleApiSources method. + + Attributes: + parent (str): + Required. The parent collection to list + GoogleApiSources on. + page_size (int): + Optional. The maximum number of results to + return on each page. + Note: The service may send fewer. + page_token (str): + Optional. The page token; provide the value from the + ``next_page_token`` field in a previous call to retrieve the + subsequent page. + + When paginating, all other parameters provided must match + the previous call that provided the page token. + order_by (str): + Optional. The sorting order of the resources returned. Value + should be a comma-separated list of fields. The default + sorting order is ascending. To specify descending order for + a field, append a ``desc`` suffix; for example: + ``name desc, update_time``. + filter (str): + Optional. The filter field that the list + request will filter on. Possible filtersare + described in https://google.aip.dev/160. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListGoogleApiSourcesResponse(proto.Message): + r"""The response message for the ``ListGoogleApiSources`` method. + + Attributes: + google_api_sources (MutableSequence[google.cloud.eventarc_v1.types.GoogleApiSource]): + The requested GoogleApiSources, up to the number specified + in ``page_size``. + next_page_token (str): + A page token that can be sent to + ``ListMessageBusEnrollments`` to request the next page. If + this is empty, then there are no more pages. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + google_api_sources: MutableSequence[ + gce_google_api_source.GoogleApiSource + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gce_google_api_source.GoogleApiSource, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateGoogleApiSourceRequest(proto.Message): + r"""The request message for the CreateGoogleApiSource method. + + Attributes: + parent (str): + Required. The parent collection in which to + add this google api source. + google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): + Required. The google api source to create. + google_api_source_id (str): + Required. The user-provided ID to be assigned to the + GoogleApiSource. It should match the format + (^`a-z <[a-z0-9-]{0,61}[a-z0-9]>`__?$). + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + google_api_source: gce_google_api_source.GoogleApiSource = proto.Field( + proto.MESSAGE, + number=2, + message=gce_google_api_source.GoogleApiSource, + ) + google_api_source_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateGoogleApiSourceRequest(proto.Message): + r"""The request message for the UpdateGoogleApiSource method. + + Attributes: + google_api_source (google.cloud.eventarc_v1.types.GoogleApiSource): + Required. The GoogleApiSource to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The fields to be updated; only fields explicitly + provided are updated. If no field mask is provided, all + provided fields in the request are updated. To update all + fields, provide a field mask of "*". + allow_missing (bool): + Optional. If set to true, and the GoogleApiSource is not + found, a new GoogleApiSource will be created. In this + situation, ``update_mask`` is ignored. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + google_api_source: gce_google_api_source.GoogleApiSource = proto.Field( + proto.MESSAGE, + number=1, + message=gce_google_api_source.GoogleApiSource, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteGoogleApiSourceRequest(proto.Message): + r"""The request message for the DeleteGoogleApiSource method. + + Attributes: + name (str): + Required. The name of the GoogleApiSource to + be deleted. + etag (str): + Optional. If provided, the MessageBus will + only be deleted if the etag matches the current + etag on the resource. + allow_missing (bool): + Optional. If set to true, and the MessageBus + is not found, the request will succeed but no + action will be taken on the server. + validate_only (bool): + Optional. If set, validate the request and + preview the review, but do not post it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + class OperationMetadata(proto.Message): r"""Represents the metadata of the long-running operation. diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/google_api_source.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/google_api_source.py new file mode 100644 index 000000000000..99c5643bbb5f --- /dev/null +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/google_api_source.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.eventarc_v1.types import logging_config as gce_logging_config + +__protobuf__ = proto.module( + package="google.cloud.eventarc.v1", + manifest={ + "GoogleApiSource", + }, +) + + +class GoogleApiSource(proto.Message): + r"""A GoogleApiSource represents a subscription of 1P events from + a MessageBus. + + Attributes: + name (str): + Identifier. Resource name of the form + projects/{project}/locations/{location}/googleApiSources/{google_api_source} + uid (str): + Output only. Server assigned unique + identifier for the channel. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on update and delete requests + to ensure that the client has an up-to-date + value before proceeding. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + labels (MutableMapping[str, str]): + Optional. Resource labels. + annotations (MutableMapping[str, str]): + Optional. Resource annotations. + display_name (str): + Optional. Resource display name. + destination (str): + Required. Destination is the message bus that the + GoogleApiSource is delivering to. It must be point to the + full resource name of a MessageBus. Format: + "projects/{PROJECT_ID}/locations/{region}/messagesBuses/{MESSAGE_BUS_ID) + crypto_key_name (str): + Optional. Resource name of a KMS crypto key (managed by the + user) used to encrypt/decrypt their event data. + + It must match the pattern + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + logging_config (google.cloud.eventarc_v1.types.LoggingConfig): + Optional. Config to control Platform logging + for the GoogleApiSource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + destination: str = proto.Field( + proto.STRING, + number=9, + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=10, + ) + logging_config: gce_logging_config.LoggingConfig = proto.Field( + proto.MESSAGE, + number=11, + message=gce_logging_config.LoggingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/logging_config.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/logging_config.py new file mode 100644 index 000000000000..edc5f4c09175 --- /dev/null +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/logging_config.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.eventarc.v1", + manifest={ + "LoggingConfig", + }, +) + + +class LoggingConfig(proto.Message): + r"""The configuration for Platform Telemetry logging for Eventarc + Avdvanced resources. + + Attributes: + log_severity (google.cloud.eventarc_v1.types.LoggingConfig.LogSeverity): + Optional. The minimum severity of logs that + will be sent to Stackdriver/Platform Telemetry. + Logs at severitiy ≥ this value will be sent, + unless it is NONE. + """ + + class LogSeverity(proto.Enum): + r"""The different severities for logging supported by Eventarc + Advanced resources. + This enum is an exhaustive list of log severities and is FROZEN. + Do not expect new values to be added. + + Values: + LOG_SEVERITY_UNSPECIFIED (0): + Log severity is not specified. This value is treated the + same as NONE, but is used to distinguish between no update + and update to NONE in update_masks. + NONE (1): + Default value at resource creation, presence + of this value must be treated as no + logging/disable logging. + DEBUG (2): + Debug or trace level logging. + INFO (3): + Routine information, such as ongoing status + or performance. + NOTICE (4): + Normal but significant events, such as start + up, shut down, or a configuration change. + WARNING (5): + Warning events might cause problems. + ERROR (6): + Error events are likely to cause problems. + CRITICAL (7): + Critical events cause more severe problems or + outages. + ALERT (8): + A person must take action immediately. + EMERGENCY (9): + One or more systems are unusable. + """ + LOG_SEVERITY_UNSPECIFIED = 0 + NONE = 1 + DEBUG = 2 + INFO = 3 + NOTICE = 4 + WARNING = 5 + ERROR = 6 + CRITICAL = 7 + ALERT = 8 + EMERGENCY = 9 + + log_severity: LogSeverity = proto.Field( + proto.ENUM, + number=1, + enum=LogSeverity, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/message_bus.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/message_bus.py new file mode 100644 index 000000000000..14688b473a39 --- /dev/null +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/message_bus.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.eventarc_v1.types import logging_config as gce_logging_config + +__protobuf__ = proto.module( + package="google.cloud.eventarc.v1", + manifest={ + "MessageBus", + }, +) + + +class MessageBus(proto.Message): + r"""MessageBus for the messages flowing through the system. The + admin has visibility and control over the messages being + published and consumed and can restrict publishers and + subscribers to only a subset of data available in the system by + defining authorization policies. + + Attributes: + name (str): + Identifier. Resource name of the form + projects/{project}/locations/{location}/messageBuses/{message_bus} + uid (str): + Output only. Server assigned unique + identifier for the channel. The value is a UUID4 + string and guaranteed to remain unchanged until + the resource is deleted. + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on update and delete requests + to ensure that the client has an up-to-date + value before proceeding. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + labels (MutableMapping[str, str]): + Optional. Resource labels. + annotations (MutableMapping[str, str]): + Optional. Resource annotations. + display_name (str): + Optional. Resource display name. + crypto_key_name (str): + Optional. Resource name of a KMS crypto key (managed by the + user) used to encrypt/decrypt their event data. + + It must match the pattern + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + logging_config (google.cloud.eventarc_v1.types.LoggingConfig): + Optional. Config to control Platform logging + for the Message Bus. This log configuration is + applied to the Message Bus itself, and all the + Enrollments attached to it. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=10, + ) + logging_config: gce_logging_config.LoggingConfig = proto.Field( + proto.MESSAGE, + number=11, + message=gce_logging_config.LoggingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/network_config.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/network_config.py new file mode 100644 index 000000000000..47ef79f325be --- /dev/null +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/network_config.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.eventarc.v1", + manifest={ + "NetworkConfig", + }, +) + + +class NetworkConfig(proto.Message): + r"""Network Configuration that can be inherited by other protos. + + Attributes: + network_attachment (str): + Required. Name of the NetworkAttachment that allows access + to the customer's VPC. Format: + ``projects/{PROJECT_ID}/regions/{REGION}/networkAttachments/{NETWORK_ATTACHMENT_NAME}`` + """ + + network_attachment: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/pipeline.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/pipeline.py new file mode 100644 index 000000000000..d40bb06b4386 --- /dev/null +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/pipeline.py @@ -0,0 +1,842 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.eventarc_v1.types import logging_config as gce_logging_config + +__protobuf__ = proto.module( + package="google.cloud.eventarc.v1", + manifest={ + "Pipeline", + }, +) + + +class Pipeline(proto.Message): + r"""A representation of the Pipeline resource. + + Attributes: + name (str): + Identifier. The resource name of the Pipeline. Must be + unique within the location of the project and must be in + ``projects/{project}/locations/{location}/pipelines/{pipeline}`` + format. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time. + A timestamp in RFC3339 UTC "Zulu" format, with + nanosecond resolution and up to nine fractional + digits. Examples: "2014-10-02T15:01:23Z" and + "2014-10-02T15:01:23.045123456Z". + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last-modified time. + A timestamp in RFC3339 UTC "Zulu" format, with + nanosecond resolution and up to nine fractional + digits. Examples: "2014-10-02T15:01:23Z" and + "2014-10-02T15:01:23.045123456Z". + labels (MutableMapping[str, str]): + Optional. User labels attached to the + Pipeline that can be used to group resources. An + object containing a list of "key": value pairs. + Example: { "name": "wrench", "mass": "1.3kg", + "count": "3" }. + uid (str): + Output only. Server-assigned unique + identifier for the Pipeline. The value is a + UUID4 string and guaranteed to remain unchanged + until the resource is deleted. + annotations (MutableMapping[str, str]): + Optional. User-defined annotations. See + https://google.aip.dev/128#annotations. + display_name (str): + Optional. Display name of resource. + destinations (MutableSequence[google.cloud.eventarc_v1.types.Pipeline.Destination]): + Required. List of destinations to which + messages will be forwarded. Currently, exactly + one destination is supported per Pipeline. + mediations (MutableSequence[google.cloud.eventarc_v1.types.Pipeline.Mediation]): + Optional. List of mediation operations to be + performed on the message. Currently, only one + Transformation operation is allowed in each + Pipeline. + crypto_key_name (str): + Optional. Resource name of a KMS crypto key + (managed by the user) used to encrypt/decrypt + the event data. If not set, an internal + Google-owned key will be used to encrypt + messages. It must match the pattern + "projects/{project}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}". + input_payload_format (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat): + Optional. The payload format expected for the messages + received by the Pipeline. If input_payload_format is set + then any messages not matching this format will be treated + as persistent errors. If input_payload_format is not set, + then the message data will be treated as an opaque binary + and no output format can be set on the Pipeline through the + Pipeline.Destination.output_payload_format field. Any + Mediations on the Pipeline that involve access to the data + field will fail as persistent errors. + logging_config (google.cloud.eventarc_v1.types.LoggingConfig): + Optional. Config to control Platform Logging + for Pipelines. + retry_policy (google.cloud.eventarc_v1.types.Pipeline.RetryPolicy): + Optional. The retry policy to use in the + pipeline. + etag (str): + Output only. This checksum is computed by the + server based on the value of other fields, and + might be sent only on create requests to ensure + that the client has an up-to-date value before + proceeding. + """ + + class MessagePayloadFormat(proto.Message): + r"""Represents the format of message data. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + protobuf (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.ProtobufFormat): + Optional. Protobuf format. + + This field is a member of `oneof`_ ``kind``. + avro (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.AvroFormat): + Optional. Avro format. + + This field is a member of `oneof`_ ``kind``. + json (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat.JsonFormat): + Optional. JSON format. + + This field is a member of `oneof`_ ``kind``. + """ + + class JsonFormat(proto.Message): + r"""The format of a JSON message payload.""" + + class ProtobufFormat(proto.Message): + r"""The format of a Protobuf message payload. + + Attributes: + schema_definition (str): + Optional. The entire schema definition is + stored in this field. + """ + + schema_definition: str = proto.Field( + proto.STRING, + number=1, + ) + + class AvroFormat(proto.Message): + r"""The format of an AVRO message payload. + + Attributes: + schema_definition (str): + Optional. The entire schema definition is + stored in this field. + """ + + schema_definition: str = proto.Field( + proto.STRING, + number=1, + ) + + protobuf: "Pipeline.MessagePayloadFormat.ProtobufFormat" = proto.Field( + proto.MESSAGE, + number=1, + oneof="kind", + message="Pipeline.MessagePayloadFormat.ProtobufFormat", + ) + avro: "Pipeline.MessagePayloadFormat.AvroFormat" = proto.Field( + proto.MESSAGE, + number=2, + oneof="kind", + message="Pipeline.MessagePayloadFormat.AvroFormat", + ) + json: "Pipeline.MessagePayloadFormat.JsonFormat" = proto.Field( + proto.MESSAGE, + number=3, + oneof="kind", + message="Pipeline.MessagePayloadFormat.JsonFormat", + ) + + class Destination(proto.Message): + r"""Represents a target of an invocation over HTTP. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_config (google.cloud.eventarc_v1.types.Pipeline.Destination.NetworkConfig): + Optional. Network config is used to configure + how Pipeline resolves and connects to a + destination. + http_endpoint (google.cloud.eventarc_v1.types.Pipeline.Destination.HttpEndpoint): + Optional. An HTTP endpoint destination described by an URI. + If a DNS FQDN is provided as the endpoint, Pipeline will + create a peering zone to the consumer VPC and forward DNS + requests to the VPC specified by network config to resolve + the service endpoint. See: + https://cloud.google.com/dns/docs/zones/zones-overview#peering_zones + + This field is a member of `oneof`_ ``destination_descriptor``. + workflow (str): + Optional. The resource name of the Workflow whose Executions + are triggered by the events. The Workflow resource should be + deployed in the same project as the Pipeline. Format: + ``projects/{project}/locations/{location}/workflows/{workflow}`` + + This field is a member of `oneof`_ ``destination_descriptor``. + message_bus (str): + Optional. The resource name of the Message Bus to which + events should be published. The Message Bus resource should + exist in the same project as the Pipeline. Format: + ``projects/{project}/locations/{location}/messageBuses/{message_bus}`` + + This field is a member of `oneof`_ ``destination_descriptor``. + topic (str): + Optional. The resource name of the Pub/Sub topic to which + events should be published. Format: + ``projects/{project}/locations/{location}/topics/{topic}`` + + This field is a member of `oneof`_ ``destination_descriptor``. + authentication_config (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig): + Optional. An authentication config used to + authenticate message requests, such that + destinations can verify the source. For example, + this can be used with private GCP destinations + that require GCP credentials to access like + Cloud Run. This field is optional and should be + set only by users interested in authenticated + push + output_payload_format (google.cloud.eventarc_v1.types.Pipeline.MessagePayloadFormat): + Optional. The message format before it is delivered to the + destination. If not set, the message will be delivered in + the format it was originally delivered to the Pipeline. This + field can only be set if Pipeline.input_payload_format is + also set. + """ + + class NetworkConfig(proto.Message): + r"""Represents a network config to be used for destination + resolution and connectivity. + + Attributes: + network_attachment (str): + Required. Name of the NetworkAttachment that allows access + to the consumer VPC. Format: + ``projects/{PROJECT_ID}/regions/{REGION}/networkAttachments/{NETWORK_ATTACHMENT_NAME}`` + """ + + network_attachment: str = proto.Field( + proto.STRING, + number=1, + ) + + class HttpEndpoint(proto.Message): + r"""Represents a HTTP endpoint destination. + + Attributes: + uri (str): + Required. The URI of the HTTP enpdoint. + + The value must be a RFC2396 URI string. Examples: + ``https://svc.us-central1.p.local:8080/route``. Only the + HTTPS protocol is supported. + message_binding_template (str): + Optional. The CEL expression used to modify how the + destination-bound HTTP request is constructed. + + If a binding expression is not specified here, the message + is treated as a CloudEvent and is mapped to the HTTP request + according to the CloudEvent HTTP Protocol Binding Binary + Content Mode. In this representation, all fields except the + ``data`` and ``datacontenttype`` field on the message are + mapped to HTTP request headers with a prefix of ``ce-``. + + To construct the HTTP request payload and the value of the + content-type HTTP header, the payload format is defined as + follows: + + 1) Use the output_payload_format_type on the + Pipeline.Destination if it is set, else: + 2) Use the input_payload_format_type on the Pipeline if it + is set, else: + 3) Treat the payload as opaque binary data. + + The ``data`` field of the message is converted to the + payload format or left as-is for case 3) and then attached + as the payload of the HTTP request. The ``content-type`` + header on the HTTP request is set to the payload format type + or left empty for case 3). However, if a mediation has + updated the ``datacontenttype`` field on the message so that + it is not the same as the payload format type but it is + still a prefix of the payload format type, then the + ``content-type`` header on the HTTP request is set to this + ``datacontenttype`` value. For example, if the + ``datacontenttype`` is "application/json" and the payload + format type is "application/json; charset=utf-8", then the + ``content-type`` header on the HTTP request is set to + "application/json; charset=utf-8". + + If a non-empty binding expression is specified then this + expression is used to modify the default CloudEvent HTTP + Protocol Binding Binary Content representation. The result + of the CEL expression must be a map of key/value pairs which + is used as follows: + + - If a map named ``headers`` exists on the result of the + expression, then its key/value pairs are directly mapped + to the HTTP request headers. The headers values are + constructed from the corresponding value type’s canonical + representation. If the ``headers`` field doesn’t exist + then the resulting HTTP request will be the headers of + the CloudEvent HTTP Binding Binary Content Mode + representation of the final message. Note: If the + specified binding expression, has updated the + ``datacontenttype`` field on the message so that it is + not the same as the payload format type but it is still a + prefix of the payload format type, then the + ``content-type`` header in the ``headers`` map is set to + this ``datacontenttype`` value. + - If a field named ``body`` exists on the result of the + expression then its value is directly mapped to the body + of the request. If the value of the ``body`` field is of + type bytes or string then it is used for the HTTP request + body as-is, with no conversion. If the body field is of + any other type then it is converted to a JSON string. If + the body field does not exist then the resulting payload + of the HTTP request will be data value of the CloudEvent + HTTP Binding Binary Content Mode representation of the + final message as described earlier. + - Any other fields in the resulting expression will be + ignored. + + The CEL expression may access the incoming CloudEvent + message in its definition, as follows: + + - The ``data`` field of the incoming CloudEvent message can + be accessed using the ``message.data`` value. Subfields + of ``message.data`` may also be accessed if an + input_payload_format has been specified on the Pipeline. + - Each attribute of the incoming CloudEvent message can be + accessed using the ``message.`` value, where is + replaced with the name of the attribute. + - Existing headers can be accessed in the CEL expression + using the ``headers`` variable. The ``headers`` variable + defines a map of key/value pairs corresponding to the + HTTP headers of the CloudEvent HTTP Binding Binary + Content Mode representation of the final message as + described earlier. For example, the following CEL + expression can be used to construct an HTTP request by + adding an additional header to the HTTP headers of the + CloudEvent HTTP Binding Binary Content Mode + representation of the final message and by overwriting + the body of the request: + + :: + + { + "headers": headers.merge({"new-header-key": "new-header-value"}), + "body": "new-body" + } + + Additionally, the following CEL extension functions are + provided for use in this CEL expression: + + - toBase64Url: map.toBase64Url() -> string + + - Converts a CelValue to a base64url encoded string + + - toJsonString: map.toJsonString() -> string + + - Converts a CelValue to a JSON string + + - merge: map1.merge(map2) -> map3 + + - Merges the passed CEL map with the existing CEL map + the function is applied to. + - If the same key exists in both maps, if the key's + value is type map both maps are merged else the value + from the passed map is used. + + - denormalize: map.denormalize() -> map + + - Denormalizes a CEL map such that every value of type + map or key in the map is expanded to return a single + level map. + - The resulting keys are "." separated indices of the + map keys. + - For example: { "a": 1, "b": { "c": 2, "d": 3 } "e": + [4, 5] } .denormalize() -> { "a": 1, "b.c": 2, "b.d": + 3, "e.0": 4, "e.1": 5 } + + - setField: map.setField(key, value) -> message + + - Sets the field of the message with the given key to + the given value. + - If the field is not present it will be added. + - If the field is present it will be overwritten. + - The key can be a dot separated path to set a field in + a nested message. + - Key must be of type string. + - Value may be any valid type. + + - removeFields: map.removeFields([key1, key2, ...]) -> + message + + - Removes the fields of the map with the given keys. + - The keys can be a dot separated path to remove a field + in a nested message. + - If a key is not found it will be ignored. + - Keys must be of type string. + + - toMap: [map1, map2, ...].toMap() -> map + + - Converts a CEL list of CEL maps to a single CEL map + + - toDestinationPayloadFormat(): + message.data.toDestinationPayloadFormat() -> string or + bytes + + - Converts the message data to the destination payload + format specified in + Pipeline.Destination.output_payload_format + - This function is meant to be applied to the + message.data field. + - If the destination payload format is not set, the + function will return the message data unchanged. + + - toCloudEventJsonWithPayloadFormat: + message.toCloudEventJsonWithPayloadFormat() -> map + + - Converts a message to the corresponding structure of + JSON format for CloudEvents + - This function applies toDestinationPayloadFormat() to + the message data. It also sets the corresponding + datacontenttype of the CloudEvent, as indicated by + Pipeline.Destination.output_payload_format. If no + output_payload_format is set it will use the existing + datacontenttype on the CloudEvent if present, else + leave datacontenttype absent. + - This function expects that the content of the message + will adhere to the standard CloudEvent format. If it + doesn’t then this function will fail. + - The result is a CEL map that corresponds to the JSON + representation of the CloudEvent. To convert that data + to a JSON string it can be chained with the + toJsonString function. + + The Pipeline expects that the message it receives adheres to + the standard CloudEvent format. If it doesn’t then the + outgoing message request may fail with a persistent error. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + message_binding_template: str = proto.Field( + proto.STRING, + number=3, + ) + + class AuthenticationConfig(proto.Message): + r"""Represents a config used to authenticate message requests. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + google_oidc (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig.OidcToken): + Optional. This authenticate method will apply + Google OIDC tokens signed by a GCP service + account to the requests. + + This field is a member of `oneof`_ ``authentication_method_descriptor``. + oauth_token (google.cloud.eventarc_v1.types.Pipeline.Destination.AuthenticationConfig.OAuthToken): + Optional. If specified, an `OAuth + token `__ + will be generated and attached as an ``Authorization`` + header in the HTTP request. + + This type of authorization should generally only be used + when calling Google APIs hosted on \*.googleapis.com. + + This field is a member of `oneof`_ ``authentication_method_descriptor``. + """ + + class OidcToken(proto.Message): + r"""Represents a config used to authenticate with a Google OIDC + token using a GCP service account. Use this authentication + method to invoke your Cloud Run and Cloud Functions destinations + or HTTP endpoints that support Google OIDC. + + Attributes: + service_account (str): + Required. Service account email used to generate the OIDC + Token. The principal who calls this API must have + iam.serviceAccounts.actAs permission in the service account. + See + https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common + for more information. Eventarc service agents must have + roles/roles/iam.serviceAccountTokenCreator role to allow the + Pipeline to create OpenID tokens for authenticated requests. + audience (str): + Optional. Audience to be used to generate the + OIDC Token. The audience claim identifies the + recipient that the JWT is intended for. If + unspecified, the destination URI will be used. + """ + + service_account: str = proto.Field( + proto.STRING, + number=1, + ) + audience: str = proto.Field( + proto.STRING, + number=2, + ) + + class OAuthToken(proto.Message): + r"""Contains information needed for generating an `OAuth + token `__. + This type of authorization should generally only be used when + calling Google APIs hosted on \*.googleapis.com. + + Attributes: + service_account (str): + Required. Service account email used to generate the `OAuth + token `__. + The principal who calls this API must have + iam.serviceAccounts.actAs permission in the service account. + See + https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common + for more information. Eventarc service agents must have + roles/roles/iam.serviceAccountTokenCreator role to allow + Pipeline to create OAuth2 tokens for authenticated requests. + scope (str): + Optional. OAuth scope to be used for + generating OAuth access token. If not specified, + "https://www.googleapis.com/auth/cloud-platform" + will be used. + """ + + service_account: str = proto.Field( + proto.STRING, + number=1, + ) + scope: str = proto.Field( + proto.STRING, + number=2, + ) + + google_oidc: "Pipeline.Destination.AuthenticationConfig.OidcToken" = ( + proto.Field( + proto.MESSAGE, + number=1, + oneof="authentication_method_descriptor", + message="Pipeline.Destination.AuthenticationConfig.OidcToken", + ) + ) + oauth_token: "Pipeline.Destination.AuthenticationConfig.OAuthToken" = ( + proto.Field( + proto.MESSAGE, + number=2, + oneof="authentication_method_descriptor", + message="Pipeline.Destination.AuthenticationConfig.OAuthToken", + ) + ) + + network_config: "Pipeline.Destination.NetworkConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="Pipeline.Destination.NetworkConfig", + ) + http_endpoint: "Pipeline.Destination.HttpEndpoint" = proto.Field( + proto.MESSAGE, + number=2, + oneof="destination_descriptor", + message="Pipeline.Destination.HttpEndpoint", + ) + workflow: str = proto.Field( + proto.STRING, + number=3, + oneof="destination_descriptor", + ) + message_bus: str = proto.Field( + proto.STRING, + number=4, + oneof="destination_descriptor", + ) + topic: str = proto.Field( + proto.STRING, + number=8, + oneof="destination_descriptor", + ) + authentication_config: "Pipeline.Destination.AuthenticationConfig" = ( + proto.Field( + proto.MESSAGE, + number=5, + message="Pipeline.Destination.AuthenticationConfig", + ) + ) + output_payload_format: "Pipeline.MessagePayloadFormat" = proto.Field( + proto.MESSAGE, + number=6, + message="Pipeline.MessagePayloadFormat", + ) + + class Mediation(proto.Message): + r"""Mediation defines different ways to modify the Pipeline. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + transformation (google.cloud.eventarc_v1.types.Pipeline.Mediation.Transformation): + Optional. How the Pipeline is to transform + messages + + This field is a member of `oneof`_ ``mediation_descriptor``. + """ + + class Transformation(proto.Message): + r"""Transformation defines the way to transform an incoming + message. + + Attributes: + transformation_template (str): + Optional. The CEL expression template to apply to transform + messages. The following CEL extension functions are provided + for use in this CEL expression: + + - merge: map1.merge(map2) -> map3 + + - Merges the passed CEL map with the existing CEL map + the function is applied to. + - If the same key exists in both maps, if the key's + value is type map both maps are merged else the value + from the passed map is used. + + - denormalize: map.denormalize() -> map + + - Denormalizes a CEL map such that every value of type + map or key in the map is expanded to return a single + level map. + - The resulting keys are "." separated indices of the + map keys. + - For example: { "a": 1, "b": { "c": 2, "d": 3 } "e": + [4, 5] } .denormalize() -> { "a": 1, "b.c": 2, "b.d": + 3, "e.0": 4, "e.1": 5 } + + - setField: map.setField(key, value) -> message + + - Sets the field of the message with the given key to + the given value. + - If the field is not present it will be added. + - If the field is present it will be overwritten. + - The key can be a dot separated path to set a field in + a nested message. + - Key must be of type string. + - Value may be any valid type. + + - removeFields: map.removeFields([key1, key2, ...]) -> + message + + - Removes the fields of the map with the given keys. + - The keys can be a dot separated path to remove a field + in a nested message. + - If a key is not found it will be ignored. + - Keys must be of type string. + + - toMap: [map1, map2, ...].toMap() -> map + + - Converts a CEL list of CEL maps to a single CEL map + + - toDestinationPayloadFormat(): + message.data.toDestinationPayloadFormat() -> string or + bytes + + - Converts the message data to the destination payload + format specified in + Pipeline.Destination.output_payload_format + - This function is meant to be applied to the + message.data field. + - If the destination payload format is not set, the + function will return the message data unchanged. + + - toCloudEventJsonWithPayloadFormat: + message.toCloudEventJsonWithPayloadFormat() -> map + + - Converts a message to the corresponding structure of + JSON format for CloudEvents + - This function applies toDestinationPayloadFormat() to + the message data. It also sets the corresponding + datacontenttype of the CloudEvent, as indicated by + Pipeline.Destination.output_payload_format. If no + output_payload_format is set it will use the existing + datacontenttype on the CloudEvent if present, else + leave datacontenttype absent. + - This function expects that the content of the message + will adhere to the standard CloudEvent format. If it + doesn’t then this function will fail. + - The result is a CEL map that corresponds to the JSON + representation of the CloudEvent. To convert that data + to a JSON string it can be chained with the + toJsonString function. + """ + + transformation_template: str = proto.Field( + proto.STRING, + number=1, + ) + + transformation: "Pipeline.Mediation.Transformation" = proto.Field( + proto.MESSAGE, + number=1, + oneof="mediation_descriptor", + message="Pipeline.Mediation.Transformation", + ) + + class RetryPolicy(proto.Message): + r"""The retry policy configuration for the Pipeline. The pipeline + exponentially backs off in case the destination is non responsive or + returns a retryable error code. The default semantics are as + follows: The backoff starts with a 5 second delay and doubles the + delay after each failed attempt (10 seconds, 20 seconds, 40 seconds, + etc.). The delay is capped at 60 seconds by default. Please note + that if you set the min_retry_delay and max_retry_delay fields to + the same value this will make the duration between retries constant. + + Attributes: + max_attempts (int): + Optional. The maximum number of delivery + attempts for any message. The value must be + between 1 and 100. The default value for this + field is 5. + min_retry_delay (google.protobuf.duration_pb2.Duration): + Optional. The minimum amount of seconds to + wait between retry attempts. The value must be + between 1 and 600. The default value for this + field is 5. + max_retry_delay (google.protobuf.duration_pb2.Duration): + Optional. The maximum amount of seconds to + wait between retry attempts. The value must be + between 1 and 600. The default value for this + field is 60. + """ + + max_attempts: int = proto.Field( + proto.INT32, + number=1, + ) + min_retry_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + max_retry_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + uid: str = proto.Field( + proto.STRING, + number=5, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + display_name: str = proto.Field( + proto.STRING, + number=7, + ) + destinations: MutableSequence[Destination] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=Destination, + ) + mediations: MutableSequence[Mediation] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=Mediation, + ) + crypto_key_name: str = proto.Field( + proto.STRING, + number=10, + ) + input_payload_format: MessagePayloadFormat = proto.Field( + proto.MESSAGE, + number=11, + message=MessagePayloadFormat, + ) + logging_config: gce_logging_config.LoggingConfig = proto.Field( + proto.MESSAGE, + number=12, + message=gce_logging_config.LoggingConfig, + ) + retry_policy: RetryPolicy = proto.Field( + proto.MESSAGE, + number=13, + message=RetryPolicy, + ) + etag: str = proto.Field( + proto.STRING, + number=99, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/trigger.py b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/trigger.py index 0090527d7ba2..d52b10946235 100644 --- a/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/trigger.py +++ b/packages/google-cloud-eventarc/google/cloud/eventarc_v1/types/trigger.py @@ -21,6 +21,8 @@ from google.rpc import code_pb2 # type: ignore import proto # type: ignore +from google.cloud.eventarc_v1.types import network_config as gce_network_config + __protobuf__ = proto.module( package="google.cloud.eventarc.v1", manifest={ @@ -32,6 +34,7 @@ "CloudRun", "GKE", "Pubsub", + "HttpEndpoint", }, ) @@ -64,25 +67,17 @@ class Trigger(proto.Message): trigger. The service account represents the identity of the trigger. - The principal who calls this API must have the - ``iam.serviceAccounts.actAs`` permission in the service - account. See - https://cloud.google.com/iam/docs/understanding-service-accounts?hl=en#sa_common - for more information. - - For Cloud Run destinations, this service account is used to - generate identity tokens when invoking the service. See - https://cloud.google.com/run/docs/triggering/pubsub-push#create-service-account - for information on how to invoke authenticated Cloud Run - services. To create Audit Log triggers, the service account - should also have the ``roles/eventarc.eventReceiver`` IAM - role. + The ``iam.serviceAccounts.actAs`` permission must be granted + on the service account to allow a principal to impersonate + the service account. For more information, see the `Roles + and permissions `__ + page specific to the trigger destination. destination (google.cloud.eventarc_v1.types.Destination): Required. Destination specifies where the events should be sent to. transport (google.cloud.eventarc_v1.types.Transport): Optional. To deliver messages, Eventarc might - use other GCP products as a transport + use other Google Cloud products as a transport intermediary. This field contains a reference to that transport intermediary. This information can be used for debugging purposes. @@ -98,6 +93,15 @@ class Trigger(proto.Message): conditions (MutableMapping[str, google.cloud.eventarc_v1.types.StateCondition]): Output only. The reason(s) why a trigger is in FAILED state. + event_data_content_type (str): + Optional. EventDataContentType specifies the type of payload + in MIME format that is expected from the CloudEvent data + field. This is set to ``application/json`` if the value is + not defined. + satisfies_pzs (bool): + Output only. Whether or not this Trigger + satisfies the requirements of physical zone + separation etag (str): Output only. This checksum is computed by the server based on the value of other fields, and @@ -158,6 +162,14 @@ class Trigger(proto.Message): number=15, message="StateCondition", ) + event_data_content_type: str = proto.Field( + proto.STRING, + number=16, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=19, + ) etag: str = proto.Field( proto.STRING, number=99, @@ -170,19 +182,21 @@ class EventFilter(proto.Message): Attributes: attribute (str): - Required. The name of a CloudEvents - attribute. Currently, only a subset of - attributes are supported for filtering. + Required. The name of a CloudEvents attribute. Currently, + only a subset of attributes are supported for filtering. You + can `retrieve a specific provider's supported event + types `__. - All triggers MUST provide a filter for the - 'type' attribute. + All triggers MUST provide a filter for the 'type' attribute. value (str): Required. The value for the attribute. operator (str): Optional. The operator used for matching the events with the value of the filter. If not specified, only events that have an exact key-value pair specified in the filter are matched. - The only allowed value is ``match-path-pattern``. + The allowed values are ``path_pattern`` and + ``match-path-pattern``. ``path_pattern`` is only allowed for + GCFv1 triggers. """ attribute: str = proto.Field( @@ -238,10 +252,14 @@ class Destination(proto.Message): This field is a member of `oneof`_ ``descriptor``. cloud_function (str): - The Cloud Function resource name. Only Cloud Functions V2 is - supported. Format: + The Cloud Function resource name. Cloud Functions V1 and V2 + are supported. Format: ``projects/{project}/locations/{location}/functions/{function}`` + This is a read-only field. Creating Cloud Functions V1/V2 + triggers is only supported via the Cloud Functions product. + An error will be returned if the user sets this value. + This field is a member of `oneof`_ ``descriptor``. gke (google.cloud.eventarc_v1.types.GKE): A GKE service capable of receiving events. @@ -256,6 +274,16 @@ class Destination(proto.Message): ``projects/{project}/locations/{location}/workflows/{workflow}`` This field is a member of `oneof`_ ``descriptor``. + http_endpoint (google.cloud.eventarc_v1.types.HttpEndpoint): + An HTTP endpoint destination described by an + URI. + + This field is a member of `oneof`_ ``descriptor``. + network_config (google.cloud.eventarc_v1.types.NetworkConfig): + Optional. Network config is used to configure + how Eventarc resolves and connect to a + destination. This should only be used with + HttpEndpoint destination type. """ cloud_run: "CloudRun" = proto.Field( @@ -280,6 +308,17 @@ class Destination(proto.Message): number=4, oneof="descriptor", ) + http_endpoint: "HttpEndpoint" = proto.Field( + proto.MESSAGE, + number=5, + oneof="descriptor", + message="HttpEndpoint", + ) + network_config: gce_network_config.NetworkConfig = proto.Field( + proto.MESSAGE, + number=6, + message=gce_network_config.NetworkConfig, + ) class Transport(proto.Message): @@ -319,6 +358,7 @@ class CloudRun(proto.Message): path (str): Optional. The relative path on the Cloud Run service the events should be sent to. + The value must conform to the definition of a URI path segment (section 3.3 of RFC2396). Examples: "/route", "route", "route/subroute". @@ -365,6 +405,7 @@ class GKE(proto.Message): path (str): Optional. The relative path on the GKE service the events should be sent to. + The value must conform to the definition of a URI path segment (section 3.3 of RFC2396). Examples: "/route", "route", "route/subroute". @@ -422,4 +463,26 @@ class Pubsub(proto.Message): ) +class HttpEndpoint(proto.Message): + r"""Represents a HTTP endpoint destination. + + Attributes: + uri (str): + Required. The URI of the HTTP enpdoint. + + The value must be a RFC2396 URI string. Examples: + ``http://10.10.10.8:80/route``, + ``http://svc.us-central1.p.local:8080/``. Only HTTP and + HTTPS protocols are supported. The host can be either a + static IP addressable from the VPC specified by the network + config, or an internal DNS hostname of the service + resolvable via Cloud DNS. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py index 609801b7ede9..ebff0154f662 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_async.py @@ -47,7 +47,6 @@ async def sample_create_channel(): parent="parent_value", channel=channel, channel_id="channel_id_value", - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py index 36a0696246ae..de1b27e29efa 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_channel_sync.py @@ -47,7 +47,6 @@ def sample_create_channel(): parent="parent_value", channel=channel, channel_id="channel_id_value", - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py new file mode 100644 index 000000000000..7b835166e5af --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreateEnrollment +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateEnrollment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_create_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.CreateEnrollmentRequest( + parent="parent_value", + enrollment=enrollment, + enrollment_id="enrollment_id_value", + ) + + # Make the request + operation = client.create_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateEnrollment_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py new file mode 100644 index 000000000000..01f0e1796c2a --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_enrollment_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreateEnrollment +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateEnrollment_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 eventarc_v1 + + +def sample_create_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.CreateEnrollmentRequest( + parent="parent_value", + enrollment=enrollment, + enrollment_id="enrollment_id_value", + ) + + # Make the request + operation = client.create_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateEnrollment_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py new file mode 100644 index 000000000000..7499aa595d93 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreateGoogleApiSource +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateGoogleApiSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_create_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source=google_api_source, + google_api_source_id="google_api_source_id_value", + ) + + # Make the request + operation = client.create_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateGoogleApiSource_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py new file mode 100644 index 000000000000..43c341d99c69 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_google_api_source_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreateGoogleApiSource +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateGoogleApiSource_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 eventarc_v1 + + +def sample_create_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source=google_api_source, + google_api_source_id="google_api_source_id_value", + ) + + # Make the request + operation = client.create_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateGoogleApiSource_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py new file mode 100644 index 000000000000..a36aac63a329 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreateMessageBus +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateMessageBus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_create_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Make the request + operation = client.create_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateMessageBus_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py new file mode 100644 index 000000000000..c57422a9805b --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_message_bus_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreateMessageBus +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreateMessageBus_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 eventarc_v1 + + +def sample_create_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Make the request + operation = client.create_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreateMessageBus_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py new file mode 100644 index 000000000000..98e5c2bb46dc --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreatePipeline +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreatePipeline_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_create_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.CreatePipelineRequest( + parent="parent_value", + pipeline=pipeline, + pipeline_id="pipeline_id_value", + ) + + # Make the request + operation = client.create_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreatePipeline_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py new file mode 100644 index 000000000000..322d5cc27373 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_pipeline_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 CreatePipeline +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_CreatePipeline_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 eventarc_v1 + + +def sample_create_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.CreatePipelineRequest( + parent="parent_value", + pipeline=pipeline, + pipeline_id="pipeline_id_value", + ) + + # Make the request + operation = client.create_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_CreatePipeline_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py index a962abf7b2ec..441e73fc34c3 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_async.py @@ -50,7 +50,6 @@ async def sample_create_trigger(): parent="parent_value", trigger=trigger, trigger_id="trigger_id_value", - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py index 1255f73e32f0..10b2fb5c6f95 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_create_trigger_sync.py @@ -50,7 +50,6 @@ def sample_create_trigger(): parent="parent_value", trigger=trigger, trigger_id="trigger_id_value", - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py index 9dad97f48420..9b4f036e29e2 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_async.py @@ -41,7 +41,6 @@ async def sample_delete_channel(): # Initialize request argument(s) request = eventarc_v1.DeleteChannelRequest( name="name_value", - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py index f2efb782d664..eea3bbe17056 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_channel_sync.py @@ -41,7 +41,6 @@ def sample_delete_channel(): # Initialize request argument(s) request = eventarc_v1.DeleteChannelRequest( name="name_value", - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py new file mode 100644 index 000000000000..1452377cf60d --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeleteEnrollment +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteEnrollment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_delete_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteEnrollmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteEnrollment_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py new file mode 100644 index 000000000000..85644a33732f --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_enrollment_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeleteEnrollment +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteEnrollment_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 eventarc_v1 + + +def sample_delete_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteEnrollmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteEnrollment_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py new file mode 100644 index 000000000000..233bc8f978bc --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeleteGoogleApiSource +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_delete_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py new file mode 100644 index 000000000000..5036193f8da4 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_google_api_source_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeleteGoogleApiSource +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_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 eventarc_v1 + + +def sample_delete_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py new file mode 100644 index 000000000000..a9c638e332f0 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeleteMessageBus +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteMessageBus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_delete_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteMessageBusRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteMessageBus_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py new file mode 100644 index 000000000000..2d73c87e36c1 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_message_bus_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeleteMessageBus +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeleteMessageBus_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 eventarc_v1 + + +def sample_delete_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeleteMessageBusRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeleteMessageBus_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py new file mode 100644 index 000000000000..01ad54b6a7bb --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeletePipeline +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeletePipeline_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_delete_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.DeletePipelineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeletePipeline_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py new file mode 100644 index 000000000000..a74533f9472e --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_pipeline_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 DeletePipeline +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_DeletePipeline_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 eventarc_v1 + + +def sample_delete_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.DeletePipelineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_DeletePipeline_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py index c028d40e01ce..d8b0a8c4ca2c 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_async.py @@ -41,7 +41,6 @@ async def sample_delete_trigger(): # Initialize request argument(s) request = eventarc_v1.DeleteTriggerRequest( name="name_value", - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py index df0bd0efe944..50ce9d7741ac 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_delete_trigger_sync.py @@ -41,7 +41,6 @@ def sample_delete_trigger(): # Initialize request argument(s) request = eventarc_v1.DeleteTriggerRequest( name="name_value", - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py new file mode 100644 index 000000000000..60b53a3c1f60 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GetEnrollment +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetEnrollment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_get_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetEnrollmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_enrollment(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetEnrollment_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py new file mode 100644 index 000000000000..5e5cfe0be1d3 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_enrollment_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GetEnrollment +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetEnrollment_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 eventarc_v1 + + +def sample_get_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetEnrollmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_enrollment(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetEnrollment_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py new file mode 100644 index 000000000000..4d6e6a7271d0 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GetGoogleApiSource +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetGoogleApiSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_get_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_google_api_source(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetGoogleApiSource_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py new file mode 100644 index 000000000000..d48db32727b5 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_google_api_source_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GetGoogleApiSource +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetGoogleApiSource_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 eventarc_v1 + + +def sample_get_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_google_api_source(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetGoogleApiSource_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py new file mode 100644 index 000000000000..f6fa28cec89e --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GetMessageBus +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetMessageBus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_get_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetMessageBusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_message_bus(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetMessageBus_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py new file mode 100644 index 000000000000..f973b30f58a0 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_message_bus_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GetMessageBus +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetMessageBus_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 eventarc_v1 + + +def sample_get_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetMessageBusRequest( + name="name_value", + ) + + # Make the request + response = client.get_message_bus(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetMessageBus_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py new file mode 100644 index 000000000000..8b18437b7a6c --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GetPipeline +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetPipeline_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_get_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.GetPipelineRequest( + name="name_value", + ) + + # Make the request + response = await client.get_pipeline(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetPipeline_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py new file mode 100644 index 000000000000..aaeabd978963 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_get_pipeline_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 GetPipeline +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_GetPipeline_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 eventarc_v1 + + +def sample_get_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.GetPipelineRequest( + name="name_value", + ) + + # Make the request + response = client.get_pipeline(request=request) + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_GetPipeline_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py new file mode 100644 index 000000000000..a7b6705b45da --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListEnrollments +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListEnrollments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_list_enrollments(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_enrollments(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListEnrollments_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py new file mode 100644 index 000000000000..98c3c91cfb59 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_enrollments_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListEnrollments +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListEnrollments_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 eventarc_v1 + + +def sample_list_enrollments(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_enrollments(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListEnrollments_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py new file mode 100644 index 000000000000..d5190ae8997a --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListGoogleApiSources +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListGoogleApiSources_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_list_google_api_sources(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListGoogleApiSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_api_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListGoogleApiSources_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py new file mode 100644 index 000000000000..d5148cefa663 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_google_api_sources_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListGoogleApiSources +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListGoogleApiSources_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 eventarc_v1 + + +def sample_list_google_api_sources(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListGoogleApiSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_api_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListGoogleApiSources_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py new file mode 100644 index 000000000000..43db0141b579 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListMessageBusEnrollments +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_list_message_bus_enrollments(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_bus_enrollments(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py new file mode 100644 index 000000000000..54bc9ecb400a --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListMessageBusEnrollments +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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 eventarc_v1 + + +def sample_list_message_bus_enrollments(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusEnrollmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_bus_enrollments(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py new file mode 100644 index 000000000000..97f05e8fafa1 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListMessageBuses +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListMessageBuses_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_list_message_buses(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_buses(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListMessageBuses_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py new file mode 100644 index 000000000000..1b41aa44c18f --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_message_buses_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListMessageBuses +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListMessageBuses_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 eventarc_v1 + + +def sample_list_message_buses(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListMessageBusesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_buses(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListMessageBuses_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py new file mode 100644 index 000000000000..cbcbffb7ce4b --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListPipelines +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListPipelines_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_list_pipelines(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.ListPipelinesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_pipelines(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListPipelines_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py new file mode 100644 index 000000000000..7b1bcff80a83 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_list_pipelines_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListPipelines +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_ListPipelines_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 eventarc_v1 + + +def sample_list_pipelines(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.ListPipelinesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_pipelines(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END eventarc_v1_generated_Eventarc_ListPipelines_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py index 909bc26c904e..7e7c83e81fb7 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_async.py @@ -40,7 +40,6 @@ async def sample_update_channel(): # Initialize request argument(s) request = eventarc_v1.UpdateChannelRequest( - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py index c478b155f896..8aaa9399228b 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_channel_sync.py @@ -40,7 +40,6 @@ def sample_update_channel(): # Initialize request argument(s) request = eventarc_v1.UpdateChannelRequest( - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py new file mode 100644 index 000000000000..a2aff56a7155 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 UpdateEnrollment +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateEnrollment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_update_enrollment(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.UpdateEnrollmentRequest( + enrollment=enrollment, + ) + + # Make the request + operation = client.update_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateEnrollment_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py new file mode 100644 index 000000000000..ca7e0c563a30 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_enrollment_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 UpdateEnrollment +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateEnrollment_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 eventarc_v1 + + +def sample_update_enrollment(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + enrollment = eventarc_v1.Enrollment() + enrollment.cel_match = "cel_match_value" + enrollment.message_bus = "message_bus_value" + enrollment.destination = "destination_value" + + request = eventarc_v1.UpdateEnrollmentRequest( + enrollment=enrollment, + ) + + # Make the request + operation = client.update_enrollment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateEnrollment_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py new file mode 100644 index 000000000000..68a50c679ac3 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 UpdateGoogleApiSource +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_update_google_api_source(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.UpdateGoogleApiSourceRequest( + google_api_source=google_api_source, + ) + + # Make the request + operation = client.update_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py new file mode 100644 index 000000000000..eea3efe7aa5b --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_google_api_source_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 UpdateGoogleApiSource +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_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 eventarc_v1 + + +def sample_update_google_api_source(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + google_api_source = eventarc_v1.GoogleApiSource() + google_api_source.destination = "destination_value" + + request = eventarc_v1.UpdateGoogleApiSourceRequest( + google_api_source=google_api_source, + ) + + # Make the request + operation = client.update_google_api_source(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py new file mode 100644 index 000000000000..3c1b9e888f72 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 UpdateMessageBus +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateMessageBus_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_update_message_bus(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateMessageBusRequest( + ) + + # Make the request + operation = client.update_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateMessageBus_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py new file mode 100644 index 000000000000..6aa6cb75b8bd --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_message_bus_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 UpdateMessageBus +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdateMessageBus_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 eventarc_v1 + + +def sample_update_message_bus(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + request = eventarc_v1.UpdateMessageBusRequest( + ) + + # Make the request + operation = client.update_message_bus(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdateMessageBus_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py new file mode 100644 index 000000000000..76c6fed7750b --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 UpdatePipeline +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdatePipeline_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import eventarc_v1 + + +async def sample_update_pipeline(): + # Create a client + client = eventarc_v1.EventarcAsyncClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.UpdatePipelineRequest( + pipeline=pipeline, + ) + + # Make the request + operation = client.update_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdatePipeline_async] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py new file mode 100644 index 000000000000..2f70f5363ff2 --- /dev/null +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_pipeline_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 UpdatePipeline +# 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-eventarc + + +# [START eventarc_v1_generated_Eventarc_UpdatePipeline_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 eventarc_v1 + + +def sample_update_pipeline(): + # Create a client + client = eventarc_v1.EventarcClient() + + # Initialize request argument(s) + pipeline = eventarc_v1.Pipeline() + pipeline.destinations.http_endpoint.uri = "uri_value" + + request = eventarc_v1.UpdatePipelineRequest( + pipeline=pipeline, + ) + + # Make the request + operation = client.update_pipeline(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END eventarc_v1_generated_Eventarc_UpdatePipeline_sync] diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py index c237b16bf935..a1e9fd81ea67 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_async.py @@ -40,7 +40,6 @@ async def sample_update_trigger(): # Initialize request argument(s) request = eventarc_v1.UpdateTriggerRequest( - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py index bed421304638..ba49e673d74c 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py +++ b/packages/google-cloud-eventarc/samples/generated_samples/eventarc_v1_generated_eventarc_update_trigger_sync.py @@ -40,7 +40,6 @@ def sample_update_trigger(): # Initialize request argument(s) request = eventarc_v1.UpdateTriggerRequest( - validate_only=True, ) # Make the request diff --git a/packages/google-cloud-eventarc/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json b/packages/google-cloud-eventarc/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json index fc06480681e7..b7b4a9f49b70 100644 --- a/packages/google-cloud-eventarc/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json +++ b/packages/google-cloud-eventarc/samples/generated_samples/snippet_metadata_google.cloud.eventarc.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-eventarc", - "version": "1.12.0" + "version": "1.13.0" }, "snippets": [ { @@ -245,12 +245,12 @@ "regionTag": "eventarc_v1_generated_Eventarc_CreateChannel_async", "segments": [ { - "end": 62, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 61, "start": 27, "type": "SHORT" }, @@ -260,18 +260,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], @@ -333,12 +333,12 @@ "regionTag": "eventarc_v1_generated_Eventarc_CreateChannel_sync", "segments": [ { - "end": 62, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 61, "start": 27, "type": "SHORT" }, @@ -348,18 +348,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], @@ -373,30 +373,30 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_trigger", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_enrollment", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateTrigger", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateEnrollment", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "CreateTrigger" + "shortName": "CreateEnrollment" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateTriggerRequest" + "type": "google.cloud.eventarc_v1.types.CreateEnrollmentRequest" }, { "name": "parent", "type": "str" }, { - "name": "trigger", - "type": "google.cloud.eventarc_v1.types.Trigger" + "name": "enrollment", + "type": "google.cloud.eventarc_v1.types.Enrollment" }, { - "name": "trigger_id", + "name": "enrollment_id", "type": "str" }, { @@ -413,21 +413,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_trigger" + "shortName": "create_enrollment" }, - "description": "Sample for CreateTrigger", - "file": "eventarc_v1_generated_eventarc_create_trigger_async.py", + "description": "Sample for CreateEnrollment", + "file": "eventarc_v1_generated_eventarc_create_enrollment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateTrigger_async", + "regionTag": "eventarc_v1_generated_Eventarc_CreateEnrollment_async", "segments": [ { - "end": 65, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 65, + "end": 62, "start": 27, "type": "SHORT" }, @@ -437,22 +437,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 55, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 62, - "start": 56, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 66, - "start": 63, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_create_trigger_async.py" + "title": "eventarc_v1_generated_eventarc_create_enrollment_async.py" }, { "canonical": true, @@ -461,30 +461,30 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.create_trigger", + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_enrollment", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.CreateTrigger", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateEnrollment", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "CreateTrigger" + "shortName": "CreateEnrollment" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.CreateTriggerRequest" + "type": "google.cloud.eventarc_v1.types.CreateEnrollmentRequest" }, { "name": "parent", "type": "str" }, { - "name": "trigger", - "type": "google.cloud.eventarc_v1.types.Trigger" + "name": "enrollment", + "type": "google.cloud.eventarc_v1.types.Enrollment" }, { - "name": "trigger_id", + "name": "enrollment_id", "type": "str" }, { @@ -501,21 +501,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_trigger" + "shortName": "create_enrollment" }, - "description": "Sample for CreateTrigger", - "file": "eventarc_v1_generated_eventarc_create_trigger_sync.py", + "description": "Sample for CreateEnrollment", + "file": "eventarc_v1_generated_eventarc_create_enrollment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_CreateTrigger_sync", + "regionTag": "eventarc_v1_generated_Eventarc_CreateEnrollment_sync", "segments": [ { - "end": 65, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 65, + "end": 62, "start": 27, "type": "SHORT" }, @@ -525,22 +525,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 55, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 62, - "start": 56, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 66, - "start": 63, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_create_trigger_sync.py" + "title": "eventarc_v1_generated_eventarc_create_enrollment_sync.py" }, { "canonical": true, @@ -550,22 +550,30 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_channel_connection", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_google_api_source", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannelConnection", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateGoogleApiSource", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "DeleteChannelConnection" + "shortName": "CreateGoogleApiSource" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest" + "type": "google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "google_api_source", + "type": "google.cloud.eventarc_v1.types.GoogleApiSource" + }, + { + "name": "google_api_source_id", "type": "str" }, { @@ -582,21 +590,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_channel_connection" + "shortName": "create_google_api_source" }, - "description": "Sample for DeleteChannelConnection", - "file": "eventarc_v1_generated_eventarc_delete_channel_connection_async.py", + "description": "Sample for CreateGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_create_google_api_source_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannelConnection_async", + "regionTag": "eventarc_v1_generated_Eventarc_CreateGoogleApiSource_async", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -606,22 +614,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_delete_channel_connection_async.py" + "title": "eventarc_v1_generated_eventarc_create_google_api_source_async.py" }, { "canonical": true, @@ -630,22 +638,30 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_channel_connection", + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_google_api_source", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannelConnection", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateGoogleApiSource", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "DeleteChannelConnection" + "shortName": "CreateGoogleApiSource" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest" + "type": "google.cloud.eventarc_v1.types.CreateGoogleApiSourceRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "google_api_source", + "type": "google.cloud.eventarc_v1.types.GoogleApiSource" + }, + { + "name": "google_api_source_id", "type": "str" }, { @@ -662,21 +678,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_channel_connection" + "shortName": "create_google_api_source" }, - "description": "Sample for DeleteChannelConnection", - "file": "eventarc_v1_generated_eventarc_delete_channel_connection_sync.py", + "description": "Sample for CreateGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_create_google_api_source_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannelConnection_sync", + "regionTag": "eventarc_v1_generated_Eventarc_CreateGoogleApiSource_sync", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -686,22 +702,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_delete_channel_connection_sync.py" + "title": "eventarc_v1_generated_eventarc_create_google_api_source_sync.py" }, { "canonical": true, @@ -711,22 +727,30 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_channel", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_message_bus", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannel", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateMessageBus", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "DeleteChannel" + "shortName": "CreateMessageBus" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteChannelRequest" + "type": "google.cloud.eventarc_v1.types.CreateMessageBusRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "message_bus", + "type": "google.cloud.eventarc_v1.types.MessageBus" + }, + { + "name": "message_bus_id", "type": "str" }, { @@ -743,13 +767,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_channel" + "shortName": "create_message_bus" }, - "description": "Sample for DeleteChannel", - "file": "eventarc_v1_generated_eventarc_delete_channel_async.py", + "description": "Sample for CreateMessageBus", + "file": "eventarc_v1_generated_eventarc_create_message_bus_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannel_async", + "regionTag": "eventarc_v1_generated_Eventarc_CreateMessageBus_async", "segments": [ { "end": 56, @@ -782,7 +806,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_delete_channel_async.py" + "title": "eventarc_v1_generated_eventarc_create_message_bus_async.py" }, { "canonical": true, @@ -791,22 +815,30 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_channel", + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_message_bus", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannel", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateMessageBus", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "DeleteChannel" + "shortName": "CreateMessageBus" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteChannelRequest" + "type": "google.cloud.eventarc_v1.types.CreateMessageBusRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "message_bus", + "type": "google.cloud.eventarc_v1.types.MessageBus" + }, + { + "name": "message_bus_id", "type": "str" }, { @@ -823,13 +855,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_channel" + "shortName": "create_message_bus" }, - "description": "Sample for DeleteChannel", - "file": "eventarc_v1_generated_eventarc_delete_channel_sync.py", + "description": "Sample for CreateMessageBus", + "file": "eventarc_v1_generated_eventarc_create_message_bus_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannel_sync", + "regionTag": "eventarc_v1_generated_Eventarc_CreateMessageBus_sync", "segments": [ { "end": 56, @@ -862,7 +894,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_delete_channel_sync.py" + "title": "eventarc_v1_generated_eventarc_create_message_bus_sync.py" }, { "canonical": true, @@ -872,27 +904,31 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_trigger", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_pipeline", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteTrigger", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreatePipeline", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "DeleteTrigger" + "shortName": "CreatePipeline" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteTriggerRequest" + "type": "google.cloud.eventarc_v1.types.CreatePipelineRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { - "name": "allow_missing", - "type": "bool" + "name": "pipeline", + "type": "google.cloud.eventarc_v1.types.Pipeline" + }, + { + "name": "pipeline_id", + "type": "str" }, { "name": "retry", @@ -908,21 +944,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_trigger" + "shortName": "create_pipeline" }, - "description": "Sample for DeleteTrigger", - "file": "eventarc_v1_generated_eventarc_delete_trigger_async.py", + "description": "Sample for CreatePipeline", + "file": "eventarc_v1_generated_eventarc_create_pipeline_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteTrigger_async", + "regionTag": "eventarc_v1_generated_Eventarc_CreatePipeline_async", "segments": [ { - "end": 56, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 60, "start": 27, "type": "SHORT" }, @@ -932,22 +968,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_delete_trigger_async.py" + "title": "eventarc_v1_generated_eventarc_create_pipeline_async.py" }, { "canonical": true, @@ -956,27 +992,31 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_trigger", + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_pipeline", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteTrigger", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreatePipeline", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "DeleteTrigger" + "shortName": "CreatePipeline" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.DeleteTriggerRequest" + "type": "google.cloud.eventarc_v1.types.CreatePipelineRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { - "name": "allow_missing", - "type": "bool" + "name": "pipeline", + "type": "google.cloud.eventarc_v1.types.Pipeline" + }, + { + "name": "pipeline_id", + "type": "str" }, { "name": "retry", @@ -992,21 +1032,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_trigger" + "shortName": "create_pipeline" }, - "description": "Sample for DeleteTrigger", - "file": "eventarc_v1_generated_eventarc_delete_trigger_sync.py", + "description": "Sample for CreatePipeline", + "file": "eventarc_v1_generated_eventarc_create_pipeline_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_DeleteTrigger_sync", + "regionTag": "eventarc_v1_generated_Eventarc_CreatePipeline_sync", "segments": [ { - "end": 56, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1016,22 +1056,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_delete_trigger_sync.py" + "title": "eventarc_v1_generated_eventarc_create_pipeline_sync.py" }, { "canonical": true, @@ -1041,22 +1081,30 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_channel_connection", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.create_trigger", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannelConnection", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateTrigger", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetChannelConnection" + "shortName": "CreateTrigger" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetChannelConnectionRequest" + "type": "google.cloud.eventarc_v1.types.CreateTriggerRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "trigger", + "type": "google.cloud.eventarc_v1.types.Trigger" + }, + { + "name": "trigger_id", "type": "str" }, { @@ -1072,22 +1120,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.ChannelConnection", - "shortName": "get_channel_connection" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_trigger" }, - "description": "Sample for GetChannelConnection", - "file": "eventarc_v1_generated_eventarc_get_channel_connection_async.py", + "description": "Sample for CreateTrigger", + "file": "eventarc_v1_generated_eventarc_create_trigger_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetChannelConnection_async", + "regionTag": "eventarc_v1_generated_Eventarc_CreateTrigger_async", "segments": [ { - "end": 51, + "end": 64, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 64, "start": 27, "type": "SHORT" }, @@ -1097,22 +1145,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 54, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 61, + "start": 55, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 65, + "start": 62, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_channel_connection_async.py" + "title": "eventarc_v1_generated_eventarc_create_trigger_async.py" }, { "canonical": true, @@ -1121,22 +1169,30 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_channel_connection", + "fullName": "google.cloud.eventarc_v1.EventarcClient.create_trigger", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannelConnection", + "fullName": "google.cloud.eventarc.v1.Eventarc.CreateTrigger", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetChannelConnection" + "shortName": "CreateTrigger" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetChannelConnectionRequest" + "type": "google.cloud.eventarc_v1.types.CreateTriggerRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "trigger", + "type": "google.cloud.eventarc_v1.types.Trigger" + }, + { + "name": "trigger_id", "type": "str" }, { @@ -1152,22 +1208,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.ChannelConnection", - "shortName": "get_channel_connection" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_trigger" }, - "description": "Sample for GetChannelConnection", - "file": "eventarc_v1_generated_eventarc_get_channel_connection_sync.py", + "description": "Sample for CreateTrigger", + "file": "eventarc_v1_generated_eventarc_create_trigger_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetChannelConnection_sync", + "regionTag": "eventarc_v1_generated_Eventarc_CreateTrigger_sync", "segments": [ { - "end": 51, + "end": 64, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 64, "start": 27, "type": "SHORT" }, @@ -1177,22 +1233,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 54, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 61, + "start": 55, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 65, + "start": 62, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_channel_connection_sync.py" + "title": "eventarc_v1_generated_eventarc_create_trigger_sync.py" }, { "canonical": true, @@ -1202,19 +1258,19 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_channel", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_channel_connection", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannel", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannelConnection", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetChannel" + "shortName": "DeleteChannelConnection" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetChannelRequest" + "type": "google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest" }, { "name": "name", @@ -1233,22 +1289,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.Channel", - "shortName": "get_channel" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_channel_connection" }, - "description": "Sample for GetChannel", - "file": "eventarc_v1_generated_eventarc_get_channel_async.py", + "description": "Sample for DeleteChannelConnection", + "file": "eventarc_v1_generated_eventarc_delete_channel_connection_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetChannel_async", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannelConnection_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1263,17 +1319,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_channel_async.py" + "title": "eventarc_v1_generated_eventarc_delete_channel_connection_async.py" }, { "canonical": true, @@ -1282,19 +1338,19 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_channel", + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_channel_connection", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannel", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannelConnection", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetChannel" + "shortName": "DeleteChannelConnection" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetChannelRequest" + "type": "google.cloud.eventarc_v1.types.DeleteChannelConnectionRequest" }, { "name": "name", @@ -1313,22 +1369,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.Channel", - "shortName": "get_channel" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_channel_connection" }, - "description": "Sample for GetChannel", - "file": "eventarc_v1_generated_eventarc_get_channel_sync.py", + "description": "Sample for DeleteChannelConnection", + "file": "eventarc_v1_generated_eventarc_delete_channel_connection_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetChannel_sync", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannelConnection_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1343,17 +1399,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_channel_sync.py" + "title": "eventarc_v1_generated_eventarc_delete_channel_connection_sync.py" }, { "canonical": true, @@ -1363,19 +1419,19 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_google_channel_config", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_channel", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleChannelConfig", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannel", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetGoogleChannelConfig" + "shortName": "DeleteChannel" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest" + "type": "google.cloud.eventarc_v1.types.DeleteChannelRequest" }, { "name": "name", @@ -1394,22 +1450,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", - "shortName": "get_google_channel_config" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_channel" }, - "description": "Sample for GetGoogleChannelConfig", - "file": "eventarc_v1_generated_eventarc_get_google_channel_config_async.py", + "description": "Sample for DeleteChannel", + "file": "eventarc_v1_generated_eventarc_delete_channel_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_async", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannel_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1424,17 +1480,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_google_channel_config_async.py" + "title": "eventarc_v1_generated_eventarc_delete_channel_async.py" }, { "canonical": true, @@ -1443,19 +1499,19 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_google_channel_config", + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_channel", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleChannelConfig", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteChannel", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetGoogleChannelConfig" + "shortName": "DeleteChannel" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest" + "type": "google.cloud.eventarc_v1.types.DeleteChannelRequest" }, { "name": "name", @@ -1474,22 +1530,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", - "shortName": "get_google_channel_config" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_channel" }, - "description": "Sample for GetGoogleChannelConfig", - "file": "eventarc_v1_generated_eventarc_get_google_channel_config_sync.py", + "description": "Sample for DeleteChannel", + "file": "eventarc_v1_generated_eventarc_delete_channel_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_sync", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteChannel_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1504,17 +1560,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_google_channel_config_sync.py" + "title": "eventarc_v1_generated_eventarc_delete_channel_sync.py" }, { "canonical": true, @@ -1524,24 +1580,28 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_provider", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_enrollment", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetProvider", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteEnrollment", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetProvider" + "shortName": "DeleteEnrollment" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetProviderRequest" + "type": "google.cloud.eventarc_v1.types.DeleteEnrollmentRequest" }, { "name": "name", "type": "str" }, + { + "name": "etag", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1555,22 +1615,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.Provider", - "shortName": "get_provider" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_enrollment" }, - "description": "Sample for GetProvider", - "file": "eventarc_v1_generated_eventarc_get_provider_async.py", + "description": "Sample for DeleteEnrollment", + "file": "eventarc_v1_generated_eventarc_delete_enrollment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetProvider_async", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteEnrollment_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1585,17 +1645,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_provider_async.py" + "title": "eventarc_v1_generated_eventarc_delete_enrollment_async.py" }, { "canonical": true, @@ -1604,24 +1664,28 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_provider", + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_enrollment", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetProvider", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteEnrollment", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetProvider" + "shortName": "DeleteEnrollment" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetProviderRequest" + "type": "google.cloud.eventarc_v1.types.DeleteEnrollmentRequest" }, { "name": "name", "type": "str" }, + { + "name": "etag", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1635,22 +1699,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.Provider", - "shortName": "get_provider" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_enrollment" }, - "description": "Sample for GetProvider", - "file": "eventarc_v1_generated_eventarc_get_provider_sync.py", + "description": "Sample for DeleteEnrollment", + "file": "eventarc_v1_generated_eventarc_delete_enrollment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetProvider_sync", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteEnrollment_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1665,17 +1729,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_provider_sync.py" + "title": "eventarc_v1_generated_eventarc_delete_enrollment_sync.py" }, { "canonical": true, @@ -1685,24 +1749,28 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_trigger", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_google_api_source", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetTrigger", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteGoogleApiSource", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetTrigger" + "shortName": "DeleteGoogleApiSource" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetTriggerRequest" + "type": "google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest" }, { "name": "name", "type": "str" }, + { + "name": "etag", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1716,22 +1784,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.Trigger", - "shortName": "get_trigger" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_google_api_source" }, - "description": "Sample for GetTrigger", - "file": "eventarc_v1_generated_eventarc_get_trigger_async.py", + "description": "Sample for DeleteGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_delete_google_api_source_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetTrigger_async", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1746,17 +1814,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_trigger_async.py" + "title": "eventarc_v1_generated_eventarc_delete_google_api_source_async.py" }, { "canonical": true, @@ -1765,24 +1833,28 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.get_trigger", + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_google_api_source", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.GetTrigger", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteGoogleApiSource", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "GetTrigger" + "shortName": "DeleteGoogleApiSource" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.GetTriggerRequest" + "type": "google.cloud.eventarc_v1.types.DeleteGoogleApiSourceRequest" }, { "name": "name", "type": "str" }, + { + "name": "etag", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1796,22 +1868,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.Trigger", - "shortName": "get_trigger" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_google_api_source" }, - "description": "Sample for GetTrigger", - "file": "eventarc_v1_generated_eventarc_get_trigger_sync.py", + "description": "Sample for DeleteGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_delete_google_api_source_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_GetTrigger_sync", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteGoogleApiSource_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1826,17 +1898,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_get_trigger_sync.py" + "title": "eventarc_v1_generated_eventarc_delete_google_api_source_sync.py" }, { "canonical": true, @@ -1846,27 +1918,3271 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_channel_connections", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_message_bus", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannelConnections", + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteMessageBus", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "ListChannelConnections" + "shortName": "DeleteMessageBus" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.ListChannelConnectionsRequest" + "type": "google.cloud.eventarc_v1.types.DeleteMessageBusRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { - "name": "retry", - "type": "google.api_core.retry.Retry" + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_message_bus" + }, + "description": "Sample for DeleteMessageBus", + "file": "eventarc_v1_generated_eventarc_delete_message_bus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteMessageBus_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_delete_message_bus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteMessageBusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_message_bus" + }, + "description": "Sample for DeleteMessageBus", + "file": "eventarc_v1_generated_eventarc_delete_message_bus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteMessageBus_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_delete_message_bus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeletePipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeletePipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeletePipelineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_pipeline" + }, + "description": "Sample for DeletePipeline", + "file": "eventarc_v1_generated_eventarc_delete_pipeline_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeletePipeline_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_delete_pipeline_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeletePipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeletePipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeletePipelineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "etag", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_pipeline" + }, + "description": "Sample for DeletePipeline", + "file": "eventarc_v1_generated_eventarc_delete_pipeline_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeletePipeline_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_delete_pipeline_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.delete_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteTriggerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "allow_missing", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_trigger" + }, + "description": "Sample for DeleteTrigger", + "file": "eventarc_v1_generated_eventarc_delete_trigger_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteTrigger_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_delete_trigger_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.delete_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.DeleteTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "DeleteTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.DeleteTriggerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "allow_missing", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_trigger" + }, + "description": "Sample for DeleteTrigger", + "file": "eventarc_v1_generated_eventarc_delete_trigger_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_DeleteTrigger_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_delete_trigger_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_channel_connection", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannelConnection", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetChannelConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetChannelConnectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.ChannelConnection", + "shortName": "get_channel_connection" + }, + "description": "Sample for GetChannelConnection", + "file": "eventarc_v1_generated_eventarc_get_channel_connection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetChannelConnection_async", + "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": "eventarc_v1_generated_eventarc_get_channel_connection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_channel_connection", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannelConnection", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetChannelConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetChannelConnectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.ChannelConnection", + "shortName": "get_channel_connection" + }, + "description": "Sample for GetChannelConnection", + "file": "eventarc_v1_generated_eventarc_get_channel_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetChannelConnection_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": "eventarc_v1_generated_eventarc_get_channel_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetChannelRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Channel", + "shortName": "get_channel" + }, + "description": "Sample for GetChannel", + "file": "eventarc_v1_generated_eventarc_get_channel_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetChannel_async", + "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": "eventarc_v1_generated_eventarc_get_channel_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_channel", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetChannel", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetChannel" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetChannelRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Channel", + "shortName": "get_channel" + }, + "description": "Sample for GetChannel", + "file": "eventarc_v1_generated_eventarc_get_channel_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetChannel_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": "eventarc_v1_generated_eventarc_get_channel_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetEnrollmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Enrollment", + "shortName": "get_enrollment" + }, + "description": "Sample for GetEnrollment", + "file": "eventarc_v1_generated_eventarc_get_enrollment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetEnrollment_async", + "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": "eventarc_v1_generated_eventarc_get_enrollment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetEnrollmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Enrollment", + "shortName": "get_enrollment" + }, + "description": "Sample for GetEnrollment", + "file": "eventarc_v1_generated_eventarc_get_enrollment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetEnrollment_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": "eventarc_v1_generated_eventarc_get_enrollment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleApiSource", + "shortName": "get_google_api_source" + }, + "description": "Sample for GetGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_get_google_api_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleApiSource_async", + "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": "eventarc_v1_generated_eventarc_get_google_api_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetGoogleApiSourceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleApiSource", + "shortName": "get_google_api_source" + }, + "description": "Sample for GetGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_get_google_api_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleApiSource_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": "eventarc_v1_generated_eventarc_get_google_api_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_google_channel_config", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleChannelConfig", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetGoogleChannelConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", + "shortName": "get_google_channel_config" + }, + "description": "Sample for GetGoogleChannelConfig", + "file": "eventarc_v1_generated_eventarc_get_google_channel_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_async", + "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": "eventarc_v1_generated_eventarc_get_google_channel_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_google_channel_config", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetGoogleChannelConfig", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetGoogleChannelConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetGoogleChannelConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", + "shortName": "get_google_channel_config" + }, + "description": "Sample for GetGoogleChannelConfig", + "file": "eventarc_v1_generated_eventarc_get_google_channel_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetGoogleChannelConfig_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": "eventarc_v1_generated_eventarc_get_google_channel_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetMessageBusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.MessageBus", + "shortName": "get_message_bus" + }, + "description": "Sample for GetMessageBus", + "file": "eventarc_v1_generated_eventarc_get_message_bus_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetMessageBus_async", + "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": "eventarc_v1_generated_eventarc_get_message_bus_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_message_bus", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetMessageBus", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetMessageBus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetMessageBusRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.MessageBus", + "shortName": "get_message_bus" + }, + "description": "Sample for GetMessageBus", + "file": "eventarc_v1_generated_eventarc_get_message_bus_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetMessageBus_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": "eventarc_v1_generated_eventarc_get_message_bus_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetPipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetPipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetPipelineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Pipeline", + "shortName": "get_pipeline" + }, + "description": "Sample for GetPipeline", + "file": "eventarc_v1_generated_eventarc_get_pipeline_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetPipeline_async", + "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": "eventarc_v1_generated_eventarc_get_pipeline_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_pipeline", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetPipeline", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetPipeline" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetPipelineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Pipeline", + "shortName": "get_pipeline" + }, + "description": "Sample for GetPipeline", + "file": "eventarc_v1_generated_eventarc_get_pipeline_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetPipeline_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": "eventarc_v1_generated_eventarc_get_pipeline_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_provider", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetProvider", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetProvider" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetProviderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Provider", + "shortName": "get_provider" + }, + "description": "Sample for GetProvider", + "file": "eventarc_v1_generated_eventarc_get_provider_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetProvider_async", + "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": "eventarc_v1_generated_eventarc_get_provider_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_provider", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetProvider", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetProvider" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetProviderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Provider", + "shortName": "get_provider" + }, + "description": "Sample for GetProvider", + "file": "eventarc_v1_generated_eventarc_get_provider_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetProvider_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": "eventarc_v1_generated_eventarc_get_provider_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.get_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetTriggerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Trigger", + "shortName": "get_trigger" + }, + "description": "Sample for GetTrigger", + "file": "eventarc_v1_generated_eventarc_get_trigger_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetTrigger_async", + "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": "eventarc_v1_generated_eventarc_get_trigger_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.get_trigger", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.GetTrigger", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "GetTrigger" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.GetTriggerRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.types.Trigger", + "shortName": "get_trigger" + }, + "description": "Sample for GetTrigger", + "file": "eventarc_v1_generated_eventarc_get_trigger_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_GetTrigger_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": "eventarc_v1_generated_eventarc_get_trigger_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_channel_connections", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannelConnections", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListChannelConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListChannelConnectionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsAsyncPager", + "shortName": "list_channel_connections" + }, + "description": "Sample for ListChannelConnections", + "file": "eventarc_v1_generated_eventarc_list_channel_connections_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListChannelConnections_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_list_channel_connections_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_channel_connections", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannelConnections", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListChannelConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListChannelConnectionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsPager", + "shortName": "list_channel_connections" + }, + "description": "Sample for ListChannelConnections", + "file": "eventarc_v1_generated_eventarc_list_channel_connections_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListChannelConnections_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": "eventarc_v1_generated_eventarc_list_channel_connections_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_channels", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannels", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListChannels" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListChannelsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsAsyncPager", + "shortName": "list_channels" + }, + "description": "Sample for ListChannels", + "file": "eventarc_v1_generated_eventarc_list_channels_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListChannels_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_list_channels_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_channels", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannels", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListChannels" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListChannelsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsPager", + "shortName": "list_channels" + }, + "description": "Sample for ListChannels", + "file": "eventarc_v1_generated_eventarc_list_channels_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListChannels_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": "eventarc_v1_generated_eventarc_list_channels_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_enrollments", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListEnrollments", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListEnrollments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListEnrollmentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsAsyncPager", + "shortName": "list_enrollments" + }, + "description": "Sample for ListEnrollments", + "file": "eventarc_v1_generated_eventarc_list_enrollments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListEnrollments_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_list_enrollments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_enrollments", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListEnrollments", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListEnrollments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListEnrollmentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListEnrollmentsPager", + "shortName": "list_enrollments" + }, + "description": "Sample for ListEnrollments", + "file": "eventarc_v1_generated_eventarc_list_enrollments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListEnrollments_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": "eventarc_v1_generated_eventarc_list_enrollments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_google_api_sources", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListGoogleApiSources", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListGoogleApiSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesAsyncPager", + "shortName": "list_google_api_sources" + }, + "description": "Sample for ListGoogleApiSources", + "file": "eventarc_v1_generated_eventarc_list_google_api_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListGoogleApiSources_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_list_google_api_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_google_api_sources", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListGoogleApiSources", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListGoogleApiSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListGoogleApiSourcesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListGoogleApiSourcesPager", + "shortName": "list_google_api_sources" + }, + "description": "Sample for ListGoogleApiSources", + "file": "eventarc_v1_generated_eventarc_list_google_api_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListGoogleApiSources_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": "eventarc_v1_generated_eventarc_list_google_api_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_message_bus_enrollments", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBusEnrollments", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListMessageBusEnrollments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsAsyncPager", + "shortName": "list_message_bus_enrollments" + }, + "description": "Sample for ListMessageBusEnrollments", + "file": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_message_bus_enrollments", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBusEnrollments", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListMessageBusEnrollments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListMessageBusEnrollmentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusEnrollmentsPager", + "shortName": "list_message_bus_enrollments" + }, + "description": "Sample for ListMessageBusEnrollments", + "file": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBusEnrollments_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": "eventarc_v1_generated_eventarc_list_message_bus_enrollments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_message_buses", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBuses", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListMessageBuses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListMessageBusesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesAsyncPager", + "shortName": "list_message_buses" + }, + "description": "Sample for ListMessageBuses", + "file": "eventarc_v1_generated_eventarc_list_message_buses_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBuses_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_list_message_buses_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_message_buses", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListMessageBuses", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListMessageBuses" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListMessageBusesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListMessageBusesPager", + "shortName": "list_message_buses" + }, + "description": "Sample for ListMessageBuses", + "file": "eventarc_v1_generated_eventarc_list_message_buses_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListMessageBuses_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": "eventarc_v1_generated_eventarc_list_message_buses_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_pipelines", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListPipelines", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListPipelines" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListPipelinesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesAsyncPager", + "shortName": "list_pipelines" + }, + "description": "Sample for ListPipelines", + "file": "eventarc_v1_generated_eventarc_list_pipelines_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListPipelines_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_list_pipelines_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_pipelines", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListPipelines", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListPipelines" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListPipelinesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListPipelinesPager", + "shortName": "list_pipelines" + }, + "description": "Sample for ListPipelines", + "file": "eventarc_v1_generated_eventarc_list_pipelines_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListPipelines_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": "eventarc_v1_generated_eventarc_list_pipelines_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_providers", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListProviders", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListProviders" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListProvidersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersAsyncPager", + "shortName": "list_providers" + }, + "description": "Sample for ListProviders", + "file": "eventarc_v1_generated_eventarc_list_providers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListProviders_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_list_providers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_providers", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListProviders", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListProviders" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListProvidersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersPager", + "shortName": "list_providers" + }, + "description": "Sample for ListProviders", + "file": "eventarc_v1_generated_eventarc_list_providers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_ListProviders_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": "eventarc_v1_generated_eventarc_list_providers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_triggers", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.ListTriggers", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "ListTriggers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.ListTriggersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" }, { "name": "timeout", @@ -1877,14 +5193,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsAsyncPager", - "shortName": "list_channel_connections" + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersAsyncPager", + "shortName": "list_triggers" }, - "description": "Sample for ListChannelConnections", - "file": "eventarc_v1_generated_eventarc_list_channel_connections_async.py", + "description": "Sample for ListTriggers", + "file": "eventarc_v1_generated_eventarc_list_triggers_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListChannelConnections_async", + "regionTag": "eventarc_v1_generated_Eventarc_ListTriggers_async", "segments": [ { "end": 52, @@ -1917,7 +5233,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_list_channel_connections_async.py" + "title": "eventarc_v1_generated_eventarc_list_triggers_async.py" }, { "canonical": true, @@ -1926,19 +5242,19 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_channel_connections", + "fullName": "google.cloud.eventarc_v1.EventarcClient.list_triggers", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannelConnections", + "fullName": "google.cloud.eventarc.v1.Eventarc.ListTriggers", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "ListChannelConnections" + "shortName": "ListTriggers" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.ListChannelConnectionsRequest" + "type": "google.cloud.eventarc_v1.types.ListTriggersRequest" }, { "name": "parent", @@ -1957,14 +5273,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelConnectionsPager", - "shortName": "list_channel_connections" + "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersPager", + "shortName": "list_triggers" }, - "description": "Sample for ListChannelConnections", - "file": "eventarc_v1_generated_eventarc_list_channel_connections_sync.py", + "description": "Sample for ListTriggers", + "file": "eventarc_v1_generated_eventarc_list_triggers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListChannelConnections_sync", + "regionTag": "eventarc_v1_generated_Eventarc_ListTriggers_sync", "segments": [ { "end": 52, @@ -1997,7 +5313,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_list_channel_connections_sync.py" + "title": "eventarc_v1_generated_eventarc_list_triggers_sync.py" }, { "canonical": true, @@ -2007,23 +5323,27 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_channels", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_channel", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannels", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateChannel", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "ListChannels" + "shortName": "UpdateChannel" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.ListChannelsRequest" + "type": "google.cloud.eventarc_v1.types.UpdateChannelRequest" }, { - "name": "parent", - "type": "str" + "name": "channel", + "type": "google.cloud.eventarc_v1.types.Channel" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -2038,22 +5358,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsAsyncPager", - "shortName": "list_channels" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_channel" }, - "description": "Sample for ListChannels", - "file": "eventarc_v1_generated_eventarc_list_channels_async.py", + "description": "Sample for UpdateChannel", + "file": "eventarc_v1_generated_eventarc_update_channel_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListChannels_async", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateChannel_async", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -2063,22 +5383,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_list_channels_async.py" + "title": "eventarc_v1_generated_eventarc_update_channel_async.py" }, { "canonical": true, @@ -2087,23 +5407,27 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_channels", + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_channel", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListChannels", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateChannel", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "ListChannels" + "shortName": "UpdateChannel" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.ListChannelsRequest" + "type": "google.cloud.eventarc_v1.types.UpdateChannelRequest" }, { - "name": "parent", - "type": "str" + "name": "channel", + "type": "google.cloud.eventarc_v1.types.Channel" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -2118,22 +5442,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListChannelsPager", - "shortName": "list_channels" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_channel" }, - "description": "Sample for ListChannels", - "file": "eventarc_v1_generated_eventarc_list_channels_sync.py", + "description": "Sample for UpdateChannel", + "file": "eventarc_v1_generated_eventarc_update_channel_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListChannels_sync", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateChannel_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -2143,22 +5467,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_list_channels_sync.py" + "title": "eventarc_v1_generated_eventarc_update_channel_sync.py" }, { "canonical": true, @@ -2168,23 +5492,196 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_providers", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_enrollment", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListProviders", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateEnrollment", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "ListProviders" + "shortName": "UpdateEnrollment" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.ListProvidersRequest" + "type": "google.cloud.eventarc_v1.types.UpdateEnrollmentRequest" + }, + { + "name": "enrollment", + "type": "google.cloud.eventarc_v1.types.Enrollment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_enrollment" + }, + "description": "Sample for UpdateEnrollment", + "file": "eventarc_v1_generated_eventarc_update_enrollment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateEnrollment_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_enrollment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcClient", + "shortName": "EventarcClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_enrollment", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateEnrollment", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateEnrollment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateEnrollmentRequest" + }, + { + "name": "enrollment", + "type": "google.cloud.eventarc_v1.types.Enrollment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_enrollment" + }, + "description": "Sample for UpdateEnrollment", + "file": "eventarc_v1_generated_eventarc_update_enrollment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateEnrollment_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "eventarc_v1_generated_eventarc_update_enrollment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", + "shortName": "EventarcAsyncClient" + }, + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_google_api_source", + "method": { + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleApiSource", + "service": { + "fullName": "google.cloud.eventarc.v1.Eventarc", + "shortName": "Eventarc" + }, + "shortName": "UpdateGoogleApiSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest" + }, + { + "name": "google_api_source", + "type": "google.cloud.eventarc_v1.types.GoogleApiSource" }, { - "name": "parent", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -2199,22 +5696,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersAsyncPager", - "shortName": "list_providers" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_google_api_source" }, - "description": "Sample for ListProviders", - "file": "eventarc_v1_generated_eventarc_list_providers_async.py", + "description": "Sample for UpdateGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_update_google_api_source_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListProviders_async", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_async", "segments": [ { - "end": 52, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 58, "start": 27, "type": "SHORT" }, @@ -2224,22 +5721,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_list_providers_async.py" + "title": "eventarc_v1_generated_eventarc_update_google_api_source_async.py" }, { "canonical": true, @@ -2248,23 +5745,27 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_providers", + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_google_api_source", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListProviders", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleApiSource", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "ListProviders" + "shortName": "UpdateGoogleApiSource" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.ListProvidersRequest" + "type": "google.cloud.eventarc_v1.types.UpdateGoogleApiSourceRequest" }, { - "name": "parent", - "type": "str" + "name": "google_api_source", + "type": "google.cloud.eventarc_v1.types.GoogleApiSource" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -2279,22 +5780,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListProvidersPager", - "shortName": "list_providers" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_google_api_source" }, - "description": "Sample for ListProviders", - "file": "eventarc_v1_generated_eventarc_list_providers_sync.py", + "description": "Sample for UpdateGoogleApiSource", + "file": "eventarc_v1_generated_eventarc_update_google_api_source_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListProviders_sync", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleApiSource_sync", "segments": [ { - "end": 52, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 58, "start": 27, "type": "SHORT" }, @@ -2304,22 +5805,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_list_providers_sync.py" + "title": "eventarc_v1_generated_eventarc_update_google_api_source_sync.py" }, { "canonical": true, @@ -2329,23 +5830,27 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.list_triggers", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_google_channel_config", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListTriggers", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleChannelConfig", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "ListTriggers" + "shortName": "UpdateGoogleChannelConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.ListTriggersRequest" + "type": "google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest" }, { - "name": "parent", - "type": "str" + "name": "google_channel_config", + "type": "google.cloud.eventarc_v1.types.GoogleChannelConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -2360,22 +5865,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersAsyncPager", - "shortName": "list_triggers" + "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", + "shortName": "update_google_channel_config" }, - "description": "Sample for ListTriggers", - "file": "eventarc_v1_generated_eventarc_list_triggers_async.py", + "description": "Sample for UpdateGoogleChannelConfig", + "file": "eventarc_v1_generated_eventarc_update_google_channel_config_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListTriggers_async", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_async", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -2385,22 +5890,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_list_triggers_async.py" + "title": "eventarc_v1_generated_eventarc_update_google_channel_config_async.py" }, { "canonical": true, @@ -2409,23 +5914,27 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.list_triggers", + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_google_channel_config", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.ListTriggers", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleChannelConfig", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "ListTriggers" + "shortName": "UpdateGoogleChannelConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.ListTriggersRequest" + "type": "google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest" }, { - "name": "parent", - "type": "str" + "name": "google_channel_config", + "type": "google.cloud.eventarc_v1.types.GoogleChannelConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -2440,22 +5949,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.services.eventarc.pagers.ListTriggersPager", - "shortName": "list_triggers" + "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", + "shortName": "update_google_channel_config" }, - "description": "Sample for ListTriggers", - "file": "eventarc_v1_generated_eventarc_list_triggers_sync.py", + "description": "Sample for UpdateGoogleChannelConfig", + "file": "eventarc_v1_generated_eventarc_update_google_channel_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_ListTriggers_sync", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -2465,22 +5974,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_list_triggers_sync.py" + "title": "eventarc_v1_generated_eventarc_update_google_channel_config_sync.py" }, { "canonical": true, @@ -2490,23 +5999,23 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_channel", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_message_bus", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateChannel", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateMessageBus", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "UpdateChannel" + "shortName": "UpdateMessageBus" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateChannelRequest" + "type": "google.cloud.eventarc_v1.types.UpdateMessageBusRequest" }, { - "name": "channel", - "type": "google.cloud.eventarc_v1.types.Channel" + "name": "message_bus", + "type": "google.cloud.eventarc_v1.types.MessageBus" }, { "name": "update_mask", @@ -2526,21 +6035,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_channel" + "shortName": "update_message_bus" }, - "description": "Sample for UpdateChannel", - "file": "eventarc_v1_generated_eventarc_update_channel_async.py", + "description": "Sample for UpdateMessageBus", + "file": "eventarc_v1_generated_eventarc_update_message_bus_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateChannel_async", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateMessageBus_async", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -2550,22 +6059,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_update_channel_async.py" + "title": "eventarc_v1_generated_eventarc_update_message_bus_async.py" }, { "canonical": true, @@ -2574,23 +6083,23 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_channel", + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_message_bus", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateChannel", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateMessageBus", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "UpdateChannel" + "shortName": "UpdateMessageBus" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateChannelRequest" + "type": "google.cloud.eventarc_v1.types.UpdateMessageBusRequest" }, { - "name": "channel", - "type": "google.cloud.eventarc_v1.types.Channel" + "name": "message_bus", + "type": "google.cloud.eventarc_v1.types.MessageBus" }, { "name": "update_mask", @@ -2610,21 +6119,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_channel" + "shortName": "update_message_bus" }, - "description": "Sample for UpdateChannel", - "file": "eventarc_v1_generated_eventarc_update_channel_sync.py", + "description": "Sample for UpdateMessageBus", + "file": "eventarc_v1_generated_eventarc_update_message_bus_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateChannel_sync", + "regionTag": "eventarc_v1_generated_Eventarc_UpdateMessageBus_sync", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -2634,22 +6143,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_update_channel_sync.py" + "title": "eventarc_v1_generated_eventarc_update_message_bus_sync.py" }, { "canonical": true, @@ -2659,23 +6168,23 @@ "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient", "shortName": "EventarcAsyncClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_google_channel_config", + "fullName": "google.cloud.eventarc_v1.EventarcAsyncClient.update_pipeline", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleChannelConfig", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdatePipeline", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "UpdateGoogleChannelConfig" + "shortName": "UpdatePipeline" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest" + "type": "google.cloud.eventarc_v1.types.UpdatePipelineRequest" }, { - "name": "google_channel_config", - "type": "google.cloud.eventarc_v1.types.GoogleChannelConfig" + "name": "pipeline", + "type": "google.cloud.eventarc_v1.types.Pipeline" }, { "name": "update_mask", @@ -2694,22 +6203,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", - "shortName": "update_google_channel_config" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_pipeline" }, - "description": "Sample for UpdateGoogleChannelConfig", - "file": "eventarc_v1_generated_eventarc_update_google_channel_config_async.py", + "description": "Sample for UpdatePipeline", + "file": "eventarc_v1_generated_eventarc_update_pipeline_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_async", + "regionTag": "eventarc_v1_generated_Eventarc_UpdatePipeline_async", "segments": [ { - "end": 54, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 58, "start": 27, "type": "SHORT" }, @@ -2724,17 +6233,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 51, + "end": 55, "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_update_google_channel_config_async.py" + "title": "eventarc_v1_generated_eventarc_update_pipeline_async.py" }, { "canonical": true, @@ -2743,23 +6252,23 @@ "fullName": "google.cloud.eventarc_v1.EventarcClient", "shortName": "EventarcClient" }, - "fullName": "google.cloud.eventarc_v1.EventarcClient.update_google_channel_config", + "fullName": "google.cloud.eventarc_v1.EventarcClient.update_pipeline", "method": { - "fullName": "google.cloud.eventarc.v1.Eventarc.UpdateGoogleChannelConfig", + "fullName": "google.cloud.eventarc.v1.Eventarc.UpdatePipeline", "service": { "fullName": "google.cloud.eventarc.v1.Eventarc", "shortName": "Eventarc" }, - "shortName": "UpdateGoogleChannelConfig" + "shortName": "UpdatePipeline" }, "parameters": [ { "name": "request", - "type": "google.cloud.eventarc_v1.types.UpdateGoogleChannelConfigRequest" + "type": "google.cloud.eventarc_v1.types.UpdatePipelineRequest" }, { - "name": "google_channel_config", - "type": "google.cloud.eventarc_v1.types.GoogleChannelConfig" + "name": "pipeline", + "type": "google.cloud.eventarc_v1.types.Pipeline" }, { "name": "update_mask", @@ -2778,22 +6287,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.eventarc_v1.types.GoogleChannelConfig", - "shortName": "update_google_channel_config" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_pipeline" }, - "description": "Sample for UpdateGoogleChannelConfig", - "file": "eventarc_v1_generated_eventarc_update_google_channel_config_sync.py", + "description": "Sample for UpdatePipeline", + "file": "eventarc_v1_generated_eventarc_update_pipeline_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "eventarc_v1_generated_Eventarc_UpdateGoogleChannelConfig_sync", + "regionTag": "eventarc_v1_generated_Eventarc_UpdatePipeline_sync", "segments": [ { - "end": 54, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 58, "start": 27, "type": "SHORT" }, @@ -2808,17 +6317,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 51, + "end": 55, "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "eventarc_v1_generated_eventarc_update_google_channel_config_sync.py" + "title": "eventarc_v1_generated_eventarc_update_pipeline_sync.py" }, { "canonical": true, @@ -2877,12 +6386,12 @@ "regionTag": "eventarc_v1_generated_Eventarc_UpdateTrigger_async", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -2892,18 +6401,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -2965,12 +6474,12 @@ "regionTag": "eventarc_v1_generated_Eventarc_UpdateTrigger_sync", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -2980,18 +6489,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-eventarc/scripts/fixup_eventarc_v1_keywords.py b/packages/google-cloud-eventarc/scripts/fixup_eventarc_v1_keywords.py index afc415fb519a..b6e8d0a4c266 100644 --- a/packages/google-cloud-eventarc/scripts/fixup_eventarc_v1_keywords.py +++ b/packages/google-cloud-eventarc/scripts/fixup_eventarc_v1_keywords.py @@ -41,22 +41,43 @@ class eventarcCallTransformer(cst.CSTTransformer): METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'create_channel': ('parent', 'channel', 'channel_id', 'validate_only', ), 'create_channel_connection': ('parent', 'channel_connection', 'channel_connection_id', ), + 'create_enrollment': ('parent', 'enrollment', 'enrollment_id', 'validate_only', ), + 'create_google_api_source': ('parent', 'google_api_source', 'google_api_source_id', 'validate_only', ), + 'create_message_bus': ('parent', 'message_bus', 'message_bus_id', 'validate_only', ), + 'create_pipeline': ('parent', 'pipeline', 'pipeline_id', 'validate_only', ), 'create_trigger': ('parent', 'trigger', 'trigger_id', 'validate_only', ), 'delete_channel': ('name', 'validate_only', ), 'delete_channel_connection': ('name', ), - 'delete_trigger': ('name', 'validate_only', 'etag', 'allow_missing', ), + 'delete_enrollment': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'delete_google_api_source': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'delete_message_bus': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'delete_pipeline': ('name', 'etag', 'allow_missing', 'validate_only', ), + 'delete_trigger': ('name', 'etag', 'allow_missing', 'validate_only', ), 'get_channel': ('name', ), 'get_channel_connection': ('name', ), + 'get_enrollment': ('name', ), + 'get_google_api_source': ('name', ), 'get_google_channel_config': ('name', ), + 'get_message_bus': ('name', ), + 'get_pipeline': ('name', ), 'get_provider': ('name', ), 'get_trigger': ('name', ), 'list_channel_connections': ('parent', 'page_size', 'page_token', ), 'list_channels': ('parent', 'page_size', 'page_token', 'order_by', ), + 'list_enrollments': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'list_google_api_sources': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'list_message_bus_enrollments': ('parent', 'page_size', 'page_token', ), + 'list_message_buses': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), + 'list_pipelines': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), 'list_providers': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), 'list_triggers': ('parent', 'page_size', 'page_token', 'order_by', 'filter', ), - 'update_channel': ('validate_only', 'channel', 'update_mask', ), + 'update_channel': ('channel', 'update_mask', 'validate_only', ), + 'update_enrollment': ('enrollment', 'update_mask', 'allow_missing', 'validate_only', ), + 'update_google_api_source': ('google_api_source', 'update_mask', 'allow_missing', 'validate_only', ), 'update_google_channel_config': ('google_channel_config', 'update_mask', ), - 'update_trigger': ('validate_only', 'trigger', 'update_mask', 'allow_missing', ), + 'update_message_bus': ('message_bus', 'update_mask', 'allow_missing', 'validate_only', ), + 'update_pipeline': ('pipeline', 'update_mask', 'allow_missing', 'validate_only', ), + 'update_trigger': ('trigger', 'update_mask', 'allow_missing', 'validate_only', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/packages/google-cloud-eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/google-cloud-eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index e751c8770670..1f839d79581b 100644 --- a/packages/google-cloud-eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/google-cloud-eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -65,6 +65,7 @@ from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import code_pb2 # type: ignore @@ -76,14 +77,25 @@ transports, ) from google.cloud.eventarc_v1.types import channel_connection as gce_channel_connection +from google.cloud.eventarc_v1.types import google_api_source as gce_google_api_source from google.cloud.eventarc_v1.types import ( google_channel_config as gce_google_channel_config, ) from google.cloud.eventarc_v1.types import channel from google.cloud.eventarc_v1.types import channel as gce_channel from google.cloud.eventarc_v1.types import channel_connection -from google.cloud.eventarc_v1.types import discovery, eventarc +from google.cloud.eventarc_v1.types import discovery +from google.cloud.eventarc_v1.types import enrollment +from google.cloud.eventarc_v1.types import enrollment as gce_enrollment +from google.cloud.eventarc_v1.types import eventarc +from google.cloud.eventarc_v1.types import google_api_source from google.cloud.eventarc_v1.types import google_channel_config +from google.cloud.eventarc_v1.types import logging_config +from google.cloud.eventarc_v1.types import message_bus +from google.cloud.eventarc_v1.types import message_bus as gce_message_bus +from google.cloud.eventarc_v1.types import network_config +from google.cloud.eventarc_v1.types import pipeline +from google.cloud.eventarc_v1.types import pipeline as gce_pipeline from google.cloud.eventarc_v1.types import trigger from google.cloud.eventarc_v1.types import trigger as gce_trigger @@ -1136,6 +1148,8 @@ def test_get_trigger(request_type, transport: str = "grpc"): uid="uid_value", service_account="service_account_value", channel="channel_value", + event_data_content_type="event_data_content_type_value", + satisfies_pzs=True, etag="etag_value", ) response = client.get_trigger(request) @@ -1152,6 +1166,8 @@ def test_get_trigger(request_type, transport: str = "grpc"): assert response.uid == "uid_value" assert response.service_account == "service_account_value" assert response.channel == "channel_value" + assert response.event_data_content_type == "event_data_content_type_value" + assert response.satisfies_pzs is True assert response.etag == "etag_value" @@ -1282,6 +1298,8 @@ async def test_get_trigger_async( uid="uid_value", service_account="service_account_value", channel="channel_value", + event_data_content_type="event_data_content_type_value", + satisfies_pzs=True, etag="etag_value", ) ) @@ -1299,6 +1317,8 @@ async def test_get_trigger_async( assert response.uid == "uid_value" assert response.service_account == "service_account_value" assert response.channel == "channel_value" + assert response.event_data_content_type == "event_data_content_type_value" + assert response.satisfies_pzs is True assert response.etag == "etag_value" @@ -3031,6 +3051,7 @@ def test_get_channel(request_type, transport: str = "grpc"): state=channel.Channel.State.PENDING, activation_token="activation_token_value", crypto_key_name="crypto_key_name_value", + satisfies_pzs=True, pubsub_topic="pubsub_topic_value", ) response = client.get_channel(request) @@ -3049,6 +3070,7 @@ def test_get_channel(request_type, transport: str = "grpc"): assert response.state == channel.Channel.State.PENDING assert response.activation_token == "activation_token_value" assert response.crypto_key_name == "crypto_key_name_value" + assert response.satisfies_pzs is True def test_get_channel_non_empty_request_with_auto_populated_field(): @@ -3180,6 +3202,7 @@ async def test_get_channel_async( state=channel.Channel.State.PENDING, activation_token="activation_token_value", crypto_key_name="crypto_key_name_value", + satisfies_pzs=True, ) ) response = await client.get_channel(request) @@ -3198,6 +3221,7 @@ async def test_get_channel_async( assert response.state == channel.Channel.State.PENDING assert response.activation_token == "activation_token_value" assert response.crypto_key_name == "crypto_key_name_value" + assert response.satisfies_pzs is True @pytest.mark.asyncio @@ -8067,13 +8091,85 @@ async def test_update_google_channel_config_flattened_error_async(): ) -def test_get_trigger_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetMessageBusRequest, + dict, + ], +) +def test_get_message_bus(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message_bus.MessageBus( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + crypto_key_name="crypto_key_name_value", + ) + response = client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, message_bus.MessageBus) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.crypto_key_name == "crypto_key_name_value" + + +def test_get_message_bus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.GetMessageBusRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_message_bus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetMessageBusRequest( + name="name_value", + ) + + +def test_get_message_bus_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -8081,425 +8177,342 @@ def test_get_trigger_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_trigger in client._transport._wrapped_methods + assert client._transport.get_message_bus 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_trigger] = mock_rpc - + client._transport._wrapped_methods[client._transport.get_message_bus] = mock_rpc request = {} - client.get_trigger(request) + client.get_message_bus(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_trigger(request) + client.get_message_bus(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_trigger_rest_required_fields(request_type=eventarc.GetTriggerRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["name"] = "" - 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 +@pytest.mark.asyncio +async def test_get_message_bus_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_trigger._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify required fields with default values are now present + # Ensure method has been cached + assert ( + client._client._transport.get_message_bus + in client._client._transport._wrapped_methods + ) - jsonified_request["name"] = "name_value" + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_message_bus + ] = mock_rpc - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_trigger._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + request = {} + await client.get_message_bus(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.get_message_bus(request) - # Designate an appropriate value for the returned response. - return_value = trigger.Trigger() - # 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 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = trigger.Trigger.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_get_message_bus_async( + transport: str = "grpc_asyncio", request_type=eventarc.GetMessageBusRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.get_trigger(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message_bus.MessageBus( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + crypto_key_name="crypto_key_name_value", + ) + ) + response = await client.get_message_bus(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetMessageBusRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, message_bus.MessageBus) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.crypto_key_name == "crypto_key_name_value" -def test_get_trigger_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.get_trigger._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) +@pytest.mark.asyncio +async def test_get_message_bus_async_from_dict(): + await test_get_message_bus_async(request_type=dict) -def test_get_trigger_rest_flattened(): +def test_get_message_bus_field_headers(): client = EventarcClient( 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 = trigger.Trigger() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/triggers/sample3"} + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetMessageBusRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + request.name = "name_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = trigger.Trigger.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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + call.return_value = message_bus.MessageBus() + client.get_message_bus(request) - client.get_trigger(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Establish that the 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/v1/{name=projects/*/locations/*/triggers/*}" % client.transport._host, - args[1], - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_get_trigger_rest_flattened_error(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_message_bus_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_trigger( - eventarc.GetTriggerRequest(), - name="name_value", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetMessageBusRequest() + request.name = "name_value" -def test_list_triggers_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 = EventarcClient( - 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_triggers 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. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message_bus.MessageBus() ) - client._transport._wrapped_methods[client._transport.list_triggers] = mock_rpc - - request = {} - client.list_triggers(request) + await client.get_message_bus(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_triggers(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_list_triggers_rest_required_fields(request_type=eventarc.ListTriggersRequest): - transport_class = transports.EventarcRestTransport - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_get_message_bus_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_triggers._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_triggers._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message_bus.MessageBus() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_message_bus( + name="name_value", ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + +def test_get_message_bus_flattened_error(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = eventarc.ListTriggersResponse() - # 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 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_message_bus( + eventarc.GetMessageBusRequest(), + name="name_value", + ) - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = eventarc.ListTriggersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_get_message_bus_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message_bus.MessageBus() - response = client.list_triggers(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message_bus.MessageBus() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_message_bus( + name="name_value", + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_list_triggers_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_message_bus_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.list_triggers._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_message_bus( + eventarc.GetMessageBusRequest(), + name="name_value", ) - & set(("parent",)) - ) -def test_list_triggers_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListMessageBusesRequest, + dict, + ], +) +def test_list_message_buses(request_type, transport: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # 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 = eventarc.ListTriggersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = eventarc.ListTriggersResponse.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 + response = client.list_message_buses(request) - client.list_triggers(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListMessageBusesRequest() + assert args[0] == request - # 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/v1/{parent=projects/*/locations/*}/triggers" % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_list_triggers_rest_flattened_error(transport: str = "rest"): +def test_list_message_buses_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_triggers( - eventarc.ListTriggersRequest(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.ListMessageBusesRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_message_buses(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListMessageBusesRequest( parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", ) -def test_list_triggers_rest_pager(transport: str = "rest"): - client = EventarcClient( - 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 = ( - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - trigger.Trigger(), - ], - next_page_token="abc", - ), - eventarc.ListTriggersResponse( - triggers=[], - next_page_token="def", - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - ], - next_page_token="ghi", - ), - eventarc.ListTriggersResponse( - triggers=[ - trigger.Trigger(), - trigger.Trigger(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListTriggersResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_triggers(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, trigger.Trigger) for i in results) - - pages = list(client.list_triggers(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_create_trigger_rest_use_cached_wrapped_rpc(): +def test_list_message_buses_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -8507,432 +8520,550 @@ def test_create_trigger_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_trigger in client._transport._wrapped_methods + assert ( + client._transport.list_message_buses 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.create_trigger] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_message_buses + ] = mock_rpc request = {} - client.create_trigger(request) + client.list_message_buses(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.create_trigger(request) + client.list_message_buses(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_create_trigger_rest_required_fields( - request_type=eventarc.CreateTriggerRequest, +@pytest.mark.asyncio +async def test_list_message_buses_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["trigger_id"] = "" - request_init["validate_only"] = False - 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) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped - assert "triggerId" not in jsonified_request - assert "validateOnly" not in jsonified_request + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_trigger._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.list_message_buses + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present - assert "triggerId" in jsonified_request - assert jsonified_request["triggerId"] == request_init["trigger_id"] - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == request_init["validate_only"] + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_message_buses + ] = mock_rpc - jsonified_request["parent"] = "parent_value" - jsonified_request["triggerId"] = "trigger_id_value" - jsonified_request["validateOnly"] = True + request = {} + await client.list_message_buses(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_trigger._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "trigger_id", - "validate_only", - ) - ) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "triggerId" in jsonified_request - assert jsonified_request["triggerId"] == "trigger_id_value" - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == True + await client.list_message_buses(request) - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_list_message_buses_async( + transport: str = "grpc_asyncio", request_type=eventarc.ListMessageBusesRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.create_trigger(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListMessageBusesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_message_buses(request) - expected_params = [ - ( - "triggerId", - "", - ), - ( - "validateOnly", - str(False).lower(), - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListMessageBusesRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_create_trigger_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.create_trigger._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "triggerId", - "validateOnly", - ) - ) - & set( - ( - "parent", - "trigger", - "triggerId", - "validateOnly", - ) - ) - ) +@pytest.mark.asyncio +async def test_list_message_buses_async_from_dict(): + await test_list_message_buses_async(request_type=dict) -def test_create_trigger_rest_flattened(): +def test_list_message_buses_field_headers(): client = EventarcClient( 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListMessageBusesRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - trigger=gce_trigger.Trigger(name="name_value"), - trigger_id="trigger_id_value", - ) - mock_args.update(sample_request) + request.parent = "parent_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + call.return_value = eventarc.ListMessageBusesResponse() + client.list_message_buses(request) - client.create_trigger(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Establish that the 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/v1/{parent=projects/*/locations/*}/triggers" % client.transport._host, - args[1], - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_create_trigger_rest_flattened_error(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_message_buses_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_trigger( - eventarc.CreateTriggerRequest(), - parent="parent_value", - trigger=gce_trigger.Trigger(name="name_value"), - trigger_id="trigger_id_value", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListMessageBusesRequest() + request.parent = "parent_value" -def test_update_trigger_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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListMessageBusesResponse() ) + await client.list_message_buses(request) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Ensure method has been cached - assert client._transport.update_trigger in client._transport._wrapped_methods + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # 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_trigger] = mock_rpc - request = {} - client.update_trigger(request) +def test_list_message_buses_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_message_buses( + parent="parent_value", + ) - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - client.update_trigger(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_message_buses_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_message_buses( + eventarc.ListMessageBusesRequest(), + parent="parent_value", + ) -def test_update_trigger_rest_required_fields( - request_type=eventarc.UpdateTriggerRequest, -): - transport_class = transports.EventarcRestTransport - request_init = {} - request_init["validate_only"] = False - 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) +@pytest.mark.asyncio +async def test_list_message_buses_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped - assert "validateOnly" not in jsonified_request + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusesResponse() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_trigger._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListMessageBusesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_message_buses( + parent="parent_value", + ) - # verify required fields with default values are now present - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == request_init["validate_only"] + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - jsonified_request["validateOnly"] = True - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_trigger._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "update_mask", - "validate_only", - ) +@pytest.mark.asyncio +async def test_list_message_buses_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == True + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_message_buses( + eventarc.ListMessageBusesRequest(), + parent="parent_value", + ) + +def test_list_message_buses_pager(transport_name: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token="def", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + RuntimeError, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_message_buses(request={}, retry=retry, timeout=timeout) - response = client.update_trigger(request) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - expected_params = [ - ( - "validateOnly", - str(False).lower(), - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message_bus.MessageBus) for i in results) -def test_update_trigger_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_message_buses_pages(transport_name: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - unset_fields = transport.update_trigger._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "updateMask", - "validateOnly", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token="def", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + RuntimeError, ) - & set(("validateOnly",)) - ) + pages = list(client.list_message_buses(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_update_trigger_rest_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_message_buses_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "trigger": {"name": "projects/sample1/locations/sample2/triggers/sample3"} - } - - # get truthy value for each flattened field - mock_args = dict( - trigger=gce_trigger.Trigger(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - allow_missing=True, + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token="def", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + RuntimeError, ) - mock_args.update(sample_request) + async_pager = await client.list_message_buses( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + assert len(responses) == 6 + assert all(isinstance(i, message_bus.MessageBus) for i in responses) - client.update_trigger(**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/v1/{trigger.name=projects/*/locations/*/triggers/*}" - % client.transport._host, - args[1], +@pytest.mark.asyncio +async def test_list_message_buses_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token="def", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + RuntimeError, ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_message_buses(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_update_trigger_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListMessageBusEnrollmentsRequest, + dict, + ], +) +def test_list_message_bus_enrollments(request_type, transport: str = "grpc"): client = EventarcClient( 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_trigger( - eventarc.UpdateTriggerRequest(), - trigger=gce_trigger.Trigger(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - allow_missing=True, + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusEnrollmentsResponse( + enrollments=["enrollments_value"], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) + response = client.list_message_bus_enrollments(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListMessageBusEnrollmentsRequest() + assert args[0] == request -def test_delete_trigger_rest_use_cached_wrapped_rpc(): + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusEnrollmentsPager) + assert response.enrollments == ["enrollments_value"] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_message_bus_enrollments_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.ListMessageBusEnrollmentsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_message_bus_enrollments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListMessageBusEnrollmentsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_message_bus_enrollments_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -8940,383 +9071,549 @@ def test_delete_trigger_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_trigger in client._transport._wrapped_methods + assert ( + client._transport.list_message_bus_enrollments + 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_trigger] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_message_bus_enrollments + ] = mock_rpc request = {} - client.delete_trigger(request) + client.list_message_bus_enrollments(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 + client.list_message_bus_enrollments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() - client.delete_trigger(request) + # Ensure method has been cached + assert ( + client._client._transport.list_message_bus_enrollments + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_message_bus_enrollments + ] = mock_rpc + + request = {} + await client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_message_bus_enrollments(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_trigger_rest_required_fields( - request_type=eventarc.DeleteTriggerRequest, +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_async( + transport: str = "grpc_asyncio", + request_type=eventarc.ListMessageBusEnrollmentsRequest, ): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["name"] = "" - request_init["validate_only"] = False - 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) + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped - assert "validateOnly" not in jsonified_request + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_trigger._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=["enrollments_value"], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_message_bus_enrollments(request) - # verify required fields with default values are now present - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == request_init["validate_only"] + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListMessageBusEnrollmentsRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" - jsonified_request["validateOnly"] = True + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusEnrollmentsAsyncPager) + assert response.enrollments == ["enrollments_value"] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_trigger._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "etag", - "validate_only", - ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == True +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_async_from_dict(): + await test_list_message_bus_enrollments_async(request_type=dict) + +def test_list_message_bus_enrollments_field_headers(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListMessageBusEnrollmentsRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + call.return_value = eventarc.ListMessageBusEnrollmentsResponse() + client.list_message_bus_enrollments(request) - response = client.delete_trigger(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [ - ( - "validateOnly", - str(False).lower(), - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_delete_trigger_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.delete_trigger._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "etag", - "validateOnly", - ) - ) - & set( - ( - "name", - "validateOnly", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListMessageBusEnrollmentsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListMessageBusEnrollmentsResponse() ) - ) + await client.list_message_bus_enrollments(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_delete_trigger_rest_flattened(): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_message_bus_enrollments_flattened(): client = EventarcClient( 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/triggers/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - allow_missing=True, + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusEnrollmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_message_bus_enrollments( + parent="parent_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_trigger(**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/v1/{name=projects/*/locations/*/triggers/*}" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_delete_trigger_rest_flattened_error(transport: str = "rest"): +def test_list_message_bus_enrollments_flattened_error(): client = EventarcClient( 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_trigger( - eventarc.DeleteTriggerRequest(), - name="name_value", - allow_missing=True, + client.list_message_bus_enrollments( + eventarc.ListMessageBusEnrollmentsRequest(), + parent="parent_value", ) -def test_get_channel_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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.get_channel in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListMessageBusEnrollmentsResponse() - # 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. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListMessageBusEnrollmentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_message_bus_enrollments( + parent="parent_value", ) - client._transport._wrapped_methods[client._transport.get_channel] = mock_rpc - - request = {} - client.get_channel(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - client.get_channel(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_message_bus_enrollments( + eventarc.ListMessageBusEnrollmentsRequest(), + parent="parent_value", + ) -def test_get_channel_rest_required_fields(request_type=eventarc.GetChannelRequest): - transport_class = transports.EventarcRestTransport - request_init = {} - request_init["name"] = "" - 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) +def test_list_message_bus_enrollments_pager(transport_name: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_channel._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + RuntimeError, + ) - # verify required fields with default values are now present + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_message_bus_enrollments( + request={}, retry=retry, timeout=timeout + ) - jsonified_request["name"] = "name_value" + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_channel._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, str) for i in results) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_list_message_bus_enrollments_pages(transport_name: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = channel.Channel() - # 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + RuntimeError, + ) + pages = list(client.list_message_bus_enrollments(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Convert return value to protobuf type - return_value = channel.Channel.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 +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.get_channel(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_message_bus_enrollments( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + assert len(responses) == 6 + assert all(isinstance(i, str) for i in responses) -def test_get_channel_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.get_channel._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_message_bus_enrollments(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_get_channel_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + eventarc.CreateMessageBusRequest, + dict, + ], +) +def test_create_message_bus(request_type, transport: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # 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 = channel.Channel() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = channel.Channel.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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_message_bus(request) - client.get_channel(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateMessageBusRequest() + assert args[0] == request - # 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/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_get_channel_rest_flattened_error(transport: str = "rest"): +def test_create_message_bus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_channel( - eventarc.GetChannelRequest(), - name="name_value", + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_message_bus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateMessageBusRequest( + parent="parent_value", + message_bus_id="message_bus_id_value", ) -def test_list_channels_rest_use_cached_wrapped_rpc(): +def test_create_message_bus_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -9324,250 +9621,360 @@ def test_list_channels_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_channels in client._transport._wrapped_methods + assert ( + client._transport.create_message_bus 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_channels] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.create_message_bus + ] = mock_rpc request = {} - client.list_channels(request) + client.create_message_bus(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_channels(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_message_bus(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_channels_rest_required_fields(request_type=eventarc.ListChannelsRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) +@pytest.mark.asyncio +async def test_create_message_bus_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_channels._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.create_message_bus + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_message_bus + ] = mock_rpc - jsonified_request["parent"] = "parent_value" + request = {} + await client.create_message_bus(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_channels._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "order_by", - "page_size", - "page_token", - ) - ) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_message_bus(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_message_bus_async( + transport: str = "grpc_asyncio", request_type=eventarc.CreateMessageBusRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_message_bus(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_message_bus_async_from_dict(): + await test_create_message_bus_async(request_type=dict) + + +def test_create_message_bus_field_headers(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListChannelsResponse() - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateMessageBusRequest() - # Convert return value to protobuf type - return_value = eventarc.ListChannelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_message_bus(request) - response = client.list_channels(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_list_channels_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_create_message_bus_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.list_channels._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "orderBy", - "pageSize", - "pageToken", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateMessageBusRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - & set(("parent",)) - ) + await client.create_message_bus(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_list_channels_rest_flattened(): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_message_bus_flattened(): client = EventarcClient( 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 = eventarc.ListChannelsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_message_bus( parent="parent_value", + message_bus=gce_message_bus.MessageBus(name="name_value"), + message_bus_id="message_bus_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 = eventarc.ListChannelsResponse.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 - - client.list_channels(**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/v1/{parent=projects/*/locations/*}/channels" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].message_bus + mock_val = gce_message_bus.MessageBus(name="name_value") + assert arg == mock_val + arg = args[0].message_bus_id + mock_val = "message_bus_id_value" + assert arg == mock_val -def test_list_channels_rest_flattened_error(transport: str = "rest"): +def test_create_message_bus_flattened_error(): client = EventarcClient( 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_channels( - eventarc.ListChannelsRequest(), + client.create_message_bus( + eventarc.CreateMessageBusRequest(), parent="parent_value", + message_bus=gce_message_bus.MessageBus(name="name_value"), + message_bus_id="message_bus_id_value", ) -def test_list_channels_rest_pager(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_message_bus_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = ( - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - channel.Channel(), - ], - next_page_token="abc", - ), - eventarc.ListChannelsResponse( - channels=[], - next_page_token="def", - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - ], - next_page_token="ghi", - ), - eventarc.ListChannelsResponse( - channels=[ - channel.Channel(), - channel.Channel(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Wrap the values into proper Response objs - response = tuple(eventarc.ListChannelsResponse.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 + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_message_bus( + parent="parent_value", + message_bus=gce_message_bus.MessageBus(name="name_value"), + message_bus_id="message_bus_id_value", + ) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].message_bus + mock_val = gce_message_bus.MessageBus(name="name_value") + assert arg == mock_val + arg = args[0].message_bus_id + mock_val = "message_bus_id_value" + assert arg == mock_val - pager = client.list_channels(request=sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, channel.Channel) for i in results) +@pytest.mark.asyncio +async def test_create_message_bus_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) - pages = list(client.list_channels(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_message_bus( + eventarc.CreateMessageBusRequest(), + parent="parent_value", + message_bus=gce_message_bus.MessageBus(name="name_value"), + message_bus_id="message_bus_id_value", + ) -def test_create_channel_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + eventarc.UpdateMessageBusRequest, + dict, + ], +) +def test_update_message_bus(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_message_bus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.UpdateMessageBusRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_message_bus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateMessageBusRequest() + + +def test_update_message_bus_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -9575,224 +9982,356 @@ def test_create_channel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_channel_ in client._transport._wrapped_methods + assert ( + client._transport.update_message_bus 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.create_channel_] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.update_message_bus + ] = mock_rpc request = {} - client.create_channel(request) + client.update_message_bus(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 + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_channel(request) + client.update_message_bus(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_create_channel_rest_required_fields( - request_type=eventarc.CreateChannelRequest, +@pytest.mark.asyncio +async def test_update_message_bus_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.EventarcRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["channel_id"] = "" - request_init["validate_only"] = False - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "channelId" not in jsonified_request - assert "validateOnly" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.update_message_bus + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_channel_._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_message_bus + ] = mock_rpc - # verify required fields with default values are now present - assert "channelId" in jsonified_request - assert jsonified_request["channelId"] == request_init["channel_id"] - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == request_init["validate_only"] + request = {} + await client.update_message_bus(request) - jsonified_request["parent"] = "parent_value" - jsonified_request["channelId"] = "channel_id_value" - jsonified_request["validateOnly"] = True + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_channel_._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "channel_id", - "validate_only", - ) - ) - jsonified_request.update(unset_fields) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "channelId" in jsonified_request - assert jsonified_request["channelId"] == "channel_id_value" - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == True + await client.update_message_bus(request) - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_update_message_bus_async( + transport: str = "grpc_asyncio", request_type=eventarc.UpdateMessageBusRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.create_channel(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_message_bus(request) - expected_params = [ - ( - "channelId", - "", - ), - ( - "validateOnly", - str(False).lower(), - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateMessageBusRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_create_channel_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.create_channel_._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "channelId", - "validateOnly", - ) - ) - & set( - ( - "parent", - "channel", - "channelId", - "validateOnly", - ) - ) - ) +@pytest.mark.asyncio +async def test_update_message_bus_async_from_dict(): + await test_update_message_bus_async(request_type=dict) -def test_create_channel_rest_flattened(): +def test_update_message_bus_field_headers(): client = EventarcClient( 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateMessageBusRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - channel=gce_channel.Channel(name="name_value"), - channel_id="channel_id_value", - ) - mock_args.update(sample_request) + request.message_bus.name = "name_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_message_bus(request) - client.create_channel(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "message_bus.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_message_bus_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateMessageBusRequest() + + request.message_bus.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "message_bus.name=name_value", + ) in kw["metadata"] + + +def test_update_message_bus_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_message_bus( + message_bus=gce_message_bus.MessageBus(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) # 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/v1/{parent=projects/*/locations/*}/channels" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].message_bus + mock_val = gce_message_bus.MessageBus(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -def test_create_channel_rest_flattened_error(transport: str = "rest"): +def test_update_message_bus_flattened_error(): client = EventarcClient( 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.create_channel( - eventarc.CreateChannelRequest(), - parent="parent_value", - channel=gce_channel.Channel(name="name_value"), - channel_id="channel_id_value", + client.update_message_bus( + eventarc.UpdateMessageBusRequest(), + message_bus=gce_message_bus.MessageBus(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_update_channel_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_update_message_bus_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_message_bus( + message_bus=gce_message_bus.MessageBus(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].message_bus + mock_val = gce_message_bus.MessageBus(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_message_bus_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_message_bus( + eventarc.UpdateMessageBusRequest(), + message_bus=gce_message_bus.MessageBus(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.DeleteMessageBusRequest, + dict, + ], +) +def test_delete_message_bus(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteMessageBusRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_message_bus_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.DeleteMessageBusRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_message_bus(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteMessageBusRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_message_bus_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -9800,400 +10339,403 @@ def test_update_channel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_channel in client._transport._wrapped_methods + assert ( + client._transport.delete_message_bus 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_channel] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.delete_message_bus + ] = mock_rpc request = {} - client.update_channel(request) + client.delete_message_bus(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 + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_channel(request) + client.delete_message_bus(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_channel_rest_required_fields( - request_type=eventarc.UpdateChannelRequest, +@pytest.mark.asyncio +async def test_delete_message_bus_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.EventarcRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["validate_only"] = False - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "validateOnly" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.delete_message_bus + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_channel._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_message_bus + ] = mock_rpc - # verify required fields with default values are now present - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == request_init["validate_only"] + request = {} + await client.delete_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - jsonified_request["validateOnly"] = True + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_channel._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "update_mask", - "validate_only", - ) - ) - jsonified_request.update(unset_fields) + await client.delete_message_bus(request) - # verify required fields with non-default values are left alone - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == True + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +async def test_delete_message_bus_async( + transport: str = "grpc_asyncio", request_type=eventarc.DeleteMessageBusRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_message_bus(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteMessageBusRequest() + assert args[0] == request - response = client.update_channel(request) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - expected_params = [ - ( - "validateOnly", - str(False).lower(), - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_delete_message_bus_async_from_dict(): + await test_delete_message_bus_async(request_type=dict) -def test_update_channel_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.update_channel._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "updateMask", - "validateOnly", - ) - ) - & set(("validateOnly",)) +def test_delete_message_bus_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteMessageBusRequest() -def test_update_channel_rest_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_message_bus_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = operations_pb2.Operation(name="operations/spam") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteMessageBusRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} - } + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - channel=gce_channel.Channel(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.delete_message_bus(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.update_channel(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_message_bus_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_message_bus( + name="name_value", + etag="etag_value", + ) # 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/v1/{channel.name=projects/*/locations/*/channels/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].etag + mock_val = "etag_value" + assert arg == mock_val -def test_update_channel_rest_flattened_error(transport: str = "rest"): +def test_delete_message_bus_flattened_error(): client = EventarcClient( 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_channel( - eventarc.UpdateChannelRequest(), - channel=gce_channel.Channel(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_message_bus( + eventarc.DeleteMessageBusRequest(), + name="name_value", + etag="etag_value", ) -def test_delete_channel_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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_delete_message_bus_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.delete_channel in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # 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. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_message_bus( + name="name_value", + etag="etag_value", ) - client._transport._wrapped_methods[client._transport.delete_channel] = mock_rpc - - request = {} - client.delete_channel(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() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].etag + mock_val = "etag_value" + assert arg == mock_val - client.delete_channel(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_delete_message_bus_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_message_bus( + eventarc.DeleteMessageBusRequest(), + name="name_value", + etag="etag_value", + ) -def test_delete_channel_rest_required_fields( - request_type=eventarc.DeleteChannelRequest, -): - transport_class = transports.EventarcRestTransport - request_init = {} - request_init["name"] = "" - request_init["validate_only"] = False - 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) +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetEnrollmentRequest, + dict, + ], +) +def test_get_enrollment(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # verify fields with default values are dropped - assert "validateOnly" not in jsonified_request - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_channel._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # verify required fields with default values are now present - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == request_init["validate_only"] + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = enrollment.Enrollment( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + cel_match="cel_match_value", + message_bus="message_bus_value", + destination="destination_value", + ) + response = client.get_enrollment(request) - jsonified_request["name"] = "name_value" - jsonified_request["validateOnly"] = True + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetEnrollmentRequest() + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_channel._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only",)) - jsonified_request.update(unset_fields) + # Establish that the response is the type that we expect. + assert isinstance(response, enrollment.Enrollment) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.cel_match == "cel_match_value" + assert response.message_bus == "message_bus_value" + assert response.destination == "destination_value" - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - assert "validateOnly" in jsonified_request - assert jsonified_request["validateOnly"] == True +def test_get_enrollment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_channel(request) - - expected_params = [ - ( - "validateOnly", - str(False).lower(), - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - -def test_delete_channel_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.GetEnrollmentRequest( + name="name_value", ) - unset_fields = transport.delete_channel._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("validateOnly",)) - & set( - ( - "name", - "validateOnly", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_enrollment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetEnrollmentRequest( + name="name_value", ) - ) - - -def test_delete_channel_rest_flattened(): - client = EventarcClient( - 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 = operations_pb2.Operation(name="operations/spam") - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} - # get truthy value for each flattened field - mock_args = dict( - name="name_value", +def test_get_enrollment_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - client.delete_channel(**mock_args) + # Ensure method has been cached + assert client._transport.get_enrollment in client._transport._wrapped_methods - # 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/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, - args[1], + # 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_enrollment] = mock_rpc + request = {} + client.get_enrollment(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_delete_channel_rest_flattened_error(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + client.get_enrollment(request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_channel( - eventarc.DeleteChannelRequest(), - name="name_value", - ) + # 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_provider_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_get_enrollment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -10201,174 +10743,304 @@ def test_get_provider_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_provider in client._transport._wrapped_methods + assert ( + client._client._transport.get_enrollment + in client._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_provider] = mock_rpc + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_enrollment + ] = mock_rpc request = {} - client.get_provider(request) + await client.get_enrollment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_provider(request) + await client.get_enrollment(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_provider_rest_required_fields(request_type=eventarc.GetProviderRequest): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["name"] = "" - 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) +@pytest.mark.asyncio +async def test_get_enrollment_async( + transport: str = "grpc_asyncio", request_type=eventarc.GetEnrollmentRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_provider._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + enrollment.Enrollment( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + cel_match="cel_match_value", + message_bus="message_bus_value", + destination="destination_value", + ) + ) + response = await client.get_enrollment(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetEnrollmentRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, enrollment.Enrollment) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.cel_match == "cel_match_value" + assert response.message_bus == "message_bus_value" + assert response.destination == "destination_value" - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_provider._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.asyncio +async def test_get_enrollment_async_from_dict(): + await test_get_enrollment_async(request_type=dict) + +def test_get_enrollment_field_headers(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = discovery.Provider() - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetEnrollmentRequest() - response_value = Response() - response_value.status_code = 200 + request.name = "name_value" - # Convert return value to protobuf type - return_value = discovery.Provider.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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + call.return_value = enrollment.Enrollment() + client.get_enrollment(request) - response = client.get_provider(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_get_provider_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_enrollment_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.get_provider._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetEnrollmentRequest() + request.name = "name_value" -def test_get_provider_rest_flattened(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + enrollment.Enrollment() + ) + await client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_enrollment_flattened(): client = EventarcClient( 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 = discovery.Provider() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = enrollment.Enrollment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_enrollment( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/providers/sample3" - } + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( + +def test_get_enrollment_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_enrollment( + eventarc.GetEnrollmentRequest(), name="name_value", ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = discovery.Provider.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 - client.get_provider(**mock_args) +@pytest.mark.asyncio +async def test_get_enrollment_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = enrollment.Enrollment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + enrollment.Enrollment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_enrollment( + name="name_value", + ) # 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/v1/{name=projects/*/locations/*/providers/*}" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_get_provider_rest_flattened_error(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_enrollment_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_provider( - eventarc.GetProviderRequest(), + await client.get_enrollment( + eventarc.GetEnrollmentRequest(), name="name_value", ) -def test_list_providers_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListEnrollmentsRequest, + dict, + ], +) +def test_list_enrollments(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListEnrollmentsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListEnrollmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnrollmentsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_enrollments_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.ListEnrollmentsRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_enrollments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListEnrollmentsRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", + ) + + +def test_list_enrollments_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -10376,437 +11048,523 @@ def test_list_providers_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_providers in client._transport._wrapped_methods + assert client._transport.list_enrollments 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_providers] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_enrollments + ] = mock_rpc request = {} - client.list_providers(request) + client.list_enrollments(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_providers(request) + client.list_enrollments(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_providers_rest_required_fields( - request_type=eventarc.ListProvidersRequest, +@pytest.mark.asyncio +async def test_list_enrollments_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.EventarcRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_enrollments + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_providers._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_enrollments + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_enrollments(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_providers._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) - jsonified_request.update(unset_fields) + await client.list_enrollments(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +async def test_list_enrollments_async( + transport: str = "grpc_asyncio", request_type=eventarc.ListEnrollmentsRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = eventarc.ListProvidersResponse() - # 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 + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListEnrollmentsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_enrollments(request) - # Convert return value to protobuf type - return_value = eventarc.ListProvidersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListEnrollmentsRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnrollmentsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - response = client.list_providers(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@pytest.mark.asyncio +async def test_list_enrollments_async_from_dict(): + await test_list_enrollments_async(request_type=dict) -def test_list_providers_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_enrollments_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.list_providers._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListEnrollmentsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + call.return_value = eventarc.ListEnrollmentsResponse() + client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_enrollments_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListEnrollmentsRequest() -def test_list_providers_rest_flattened(): + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListEnrollmentsResponse() + ) + await client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_enrollments_flattened(): client = EventarcClient( 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 = eventarc.ListProvidersResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListEnrollmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_enrollments( + parent="parent_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( + +def test_list_enrollments_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_enrollments( + eventarc.ListEnrollmentsRequest(), parent="parent_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 = eventarc.ListProvidersResponse.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 - client.list_providers(**mock_args) +@pytest.mark.asyncio +async def test_list_enrollments_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListEnrollmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListEnrollmentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_enrollments( + parent="parent_value", + ) # 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/v1/{parent=projects/*/locations/*}/providers" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_list_providers_rest_flattened_error(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_enrollments_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_providers( - eventarc.ListProvidersRequest(), + await client.list_enrollments( + eventarc.ListEnrollmentsRequest(), parent="parent_value", ) -def test_list_providers_rest_pager(transport: str = "rest"): +def test_list_enrollments_pager(transport_name: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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 = ( - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), - discovery.Provider(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), ], next_page_token="abc", ), - eventarc.ListProvidersResponse( - providers=[], + eventarc.ListEnrollmentsResponse( + enrollments=[], next_page_token="def", ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), ], next_page_token="ghi", ), - eventarc.ListProvidersResponse( - providers=[ - discovery.Provider(), - discovery.Provider(), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(eventarc.ListProvidersResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_enrollments(request={}, retry=retry, timeout=timeout) - pager = client.list_providers(request=sample_request) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout results = list(pager) assert len(results) == 6 - assert all(isinstance(i, discovery.Provider) for i in results) - - pages = list(client.list_providers(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + assert all(isinstance(i, enrollment.Enrollment) for i in results) -def test_get_channel_connection_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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_list_enrollments_pages(transport_name: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) - # 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_channel_connection - 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. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token="abc", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token="ghi", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + RuntimeError, ) - client._transport._wrapped_methods[ - client._transport.get_channel_connection - ] = mock_rpc - - request = {} - client.get_channel_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_channel_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - + pages = list(client.list_enrollments(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_get_channel_connection_rest_required_fields( - request_type=eventarc.GetChannelConnectionRequest, -): - transport_class = transports.EventarcRestTransport - request_init = {} - request_init["name"] = "" - 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) +@pytest.mark.asyncio +async def test_list_enrollments_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token="abc", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token="ghi", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_enrollments( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_channel_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + assert len(responses) == 6 + assert all(isinstance(i, enrollment.Enrollment) for i in responses) - # verify required fields with default values are now present - jsonified_request["name"] = "name_value" +@pytest.mark.asyncio +async def test_list_enrollments_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_channel_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_enrollments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token="abc", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token="ghi", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_enrollments(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.parametrize( + "request_type", + [ + eventarc.CreateEnrollmentRequest, + dict, + ], +) +def test_create_enrollment(request_type, transport: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = channel_connection.ChannelConnection() - # 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 = channel_connection.ChannelConnection.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 - - response = client.get_channel_connection(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_enrollment(request) -def test_get_channel_connection_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateEnrollmentRequest() + assert args[0] == request - unset_fields = transport.get_channel_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_get_channel_connection_rest_flattened(): +def test_create_enrollment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # 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 = channel_connection.ChannelConnection() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/channelConnections/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = channel_connection.ChannelConnection.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 - - client.get_channel_connection(**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/v1/{name=projects/*/locations/*/channelConnections/*}" - % client.transport._host, - args[1], - ) - - -def test_get_channel_connection_rest_flattened_error(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.CreateEnrollmentRequest( + parent="parent_value", + enrollment_id="enrollment_id_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_channel_connection( - eventarc.GetChannelConnectionRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_enrollment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateEnrollmentRequest( + parent="parent_value", + enrollment_id="enrollment_id_value", ) -def test_list_channel_connections_rest_use_cached_wrapped_rpc(): +def test_create_enrollment_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -10814,10 +11572,7 @@ def test_list_channel_connections_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_channel_connections - in client._transport._wrapped_methods - ) + assert client._transport.create_enrollment in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -10825,247 +11580,350 @@ def test_list_channel_connections_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_channel_connections + client._transport.create_enrollment ] = mock_rpc - request = {} - client.list_channel_connections(request) + client.create_enrollment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_channel_connections(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_enrollment(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_channel_connections_rest_required_fields( - request_type=eventarc.ListChannelConnectionsRequest, +@pytest.mark.asyncio +async def test_create_enrollment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.EventarcRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.create_enrollment + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_channel_connections._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_enrollment + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.create_enrollment(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_channel_connections._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_enrollment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_enrollment_async( + transport: str = "grpc_asyncio", request_type=eventarc.CreateEnrollmentRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateEnrollmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_enrollment_async_from_dict(): + await test_create_enrollment_async(request_type=dict) + +def test_create_enrollment_field_headers(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = eventarc.ListChannelConnectionsResponse() - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateEnrollmentRequest() - # Convert return value to protobuf type - return_value = eventarc.ListChannelConnectionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_enrollment(request) - response = client.list_channel_connections(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_list_channel_connections_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_create_enrollment_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.list_channel_connections._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateEnrollmentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - & set(("parent",)) - ) + await client.create_enrollment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_list_channel_connections_rest_flattened(): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_enrollment_flattened(): client = EventarcClient( 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 = eventarc.ListChannelConnectionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_enrollment( parent="parent_value", + enrollment=gce_enrollment.Enrollment(name="name_value"), + enrollment_id="enrollment_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 = eventarc.ListChannelConnectionsResponse.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 - - client.list_channel_connections(**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/v1/{parent=projects/*/locations/*}/channelConnections" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].enrollment + mock_val = gce_enrollment.Enrollment(name="name_value") + assert arg == mock_val + arg = args[0].enrollment_id + mock_val = "enrollment_id_value" + assert arg == mock_val -def test_list_channel_connections_rest_flattened_error(transport: str = "rest"): +def test_create_enrollment_flattened_error(): client = EventarcClient( 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_channel_connections( - eventarc.ListChannelConnectionsRequest(), + client.create_enrollment( + eventarc.CreateEnrollmentRequest(), parent="parent_value", + enrollment=gce_enrollment.Enrollment(name="name_value"), + enrollment_id="enrollment_id_value", ) -def test_list_channel_connections_rest_pager(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_enrollment_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = ( - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - next_page_token="abc", - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[], - next_page_token="def", - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - ], - next_page_token="ghi", - ), - eventarc.ListChannelConnectionsResponse( - channel_connections=[ - channel_connection.ChannelConnection(), - channel_connection.ChannelConnection(), - ], - ), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_enrollment( + parent="parent_value", + enrollment=gce_enrollment.Enrollment(name="name_value"), + enrollment_id="enrollment_id_value", ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - eventarc.ListChannelConnectionsResponse.to_json(x) for x in response + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].enrollment + mock_val = gce_enrollment.Enrollment(name="name_value") + assert arg == mock_val + arg = args[0].enrollment_id + mock_val = "enrollment_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_enrollment_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_enrollment( + eventarc.CreateEnrollmentRequest(), + parent="parent_value", + enrollment=gce_enrollment.Enrollment(name="name_value"), + enrollment_id="enrollment_id_value", ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} - pager = client.list_channel_connections(request=sample_request) +@pytest.mark.parametrize( + "request_type", + [ + eventarc.UpdateEnrollmentRequest, + dict, + ], +) +def test_update_enrollment(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, channel_connection.ChannelConnection) for i in results) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - pages = list(client.list_channel_connections(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_enrollment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateEnrollmentRequest() + assert args[0] == request -def test_create_channel_connection_rest_use_cached_wrapped_rpc(): + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_enrollment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.UpdateEnrollmentRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_enrollment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateEnrollmentRequest() + + +def test_update_enrollment_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -11073,10 +11931,7 @@ def test_create_channel_connection_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_channel_connection - in client._transport._wrapped_methods - ) + assert client._transport.update_enrollment in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -11084,204 +11939,346 @@ def test_create_channel_connection_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_channel_connection + client._transport.update_enrollment ] = mock_rpc - request = {} - client.create_channel_connection(request) + client.update_enrollment(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 + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_channel_connection(request) + client.update_enrollment(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_create_channel_connection_rest_required_fields( - request_type=eventarc.CreateChannelConnectionRequest, +@pytest.mark.asyncio +async def test_update_enrollment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.EventarcRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["channel_connection_id"] = "" - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "channelConnectionId" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.update_enrollment + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_channel_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_enrollment + ] = mock_rpc - # verify required fields with default values are now present - assert "channelConnectionId" in jsonified_request - assert ( - jsonified_request["channelConnectionId"] - == request_init["channel_connection_id"] + request = {} + await client.update_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_enrollment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_enrollment_async( + transport: str = "grpc_asyncio", request_type=eventarc.UpdateEnrollmentRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - jsonified_request["parent"] = "parent_value" - jsonified_request["channelConnectionId"] = "channel_connection_id_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_channel_connection._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("channel_connection_id",)) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_enrollment(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "channelConnectionId" in jsonified_request - assert jsonified_request["channelConnectionId"] == "channel_connection_id_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateEnrollmentRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_enrollment_async_from_dict(): + await test_update_enrollment_async(request_type=dict) + + +def test_update_enrollment_field_headers(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateEnrollmentRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.enrollment.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_enrollment(request) - response = client.create_channel_connection(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [ - ( - "channelConnectionId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "enrollment.name=name_value", + ) in kw["metadata"] -def test_create_channel_connection_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_update_enrollment_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.create_channel_connection._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("channelConnectionId",)) - & set( - ( - "parent", - "channelConnection", - "channelConnectionId", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateEnrollmentRequest() + + request.enrollment.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - ) + await client.update_enrollment(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_create_channel_connection_rest_flattened(): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "enrollment.name=name_value", + ) in kw["metadata"] + + +def test_update_enrollment_flattened(): client = EventarcClient( 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 = operations_pb2.Operation(name="operations/spam") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_enrollment( + enrollment=gce_enrollment.Enrollment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].enrollment + mock_val = gce_enrollment.Enrollment(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - channel_connection=gce_channel_connection.ChannelConnection( - name="name_value" - ), - channel_connection_id="channel_connection_id_value", + +def test_update_enrollment_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_enrollment( + eventarc.UpdateEnrollmentRequest(), + enrollment=gce_enrollment.Enrollment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.create_channel_connection(**mock_args) +@pytest.mark.asyncio +async def test_update_enrollment_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_enrollment( + enrollment=gce_enrollment.Enrollment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) # 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/v1/{parent=projects/*/locations/*}/channelConnections" - % client.transport._host, - args[1], + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].enrollment + mock_val = gce_enrollment.Enrollment(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_enrollment_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_enrollment( + eventarc.UpdateEnrollmentRequest(), + enrollment=gce_enrollment.Enrollment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_channel_connection_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + eventarc.DeleteEnrollmentRequest, + dict, + ], +) +def test_delete_enrollment(request_type, transport: str = "grpc"): client = EventarcClient( 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.create_channel_connection( - eventarc.CreateChannelConnectionRequest(), - parent="parent_value", - channel_connection=gce_channel_connection.ChannelConnection( - name="name_value" - ), - channel_connection_id="channel_connection_id_value", + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteEnrollmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_enrollment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.DeleteEnrollmentRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_enrollment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteEnrollmentRequest( + name="name_value", + etag="etag_value", ) -def test_delete_channel_connection_rest_use_cached_wrapped_rpc(): +def test_delete_enrollment_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 = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -11289,10 +12286,7 @@ def test_delete_channel_connection_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_channel_connection - in client._transport._wrapped_methods - ) + assert client._transport.delete_enrollment in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -11300,353 +12294,389 @@ def test_delete_channel_connection_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_channel_connection + client._transport.delete_enrollment ] = mock_rpc - request = {} - client.delete_channel_connection(request) + client.delete_enrollment(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 + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_channel_connection(request) + client.delete_enrollment(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_channel_connection_rest_required_fields( - request_type=eventarc.DeleteChannelConnectionRequest, +@pytest.mark.asyncio +async def test_delete_enrollment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.EventarcRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.delete_enrollment + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_channel_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_enrollment + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.delete_enrollment(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_channel_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_enrollment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_enrollment_async( + transport: str = "grpc_asyncio", request_type=eventarc.DeleteEnrollmentRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteEnrollmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.asyncio +async def test_delete_enrollment_async_from_dict(): + await test_delete_enrollment_async(request_type=dict) + + +def test_delete_enrollment_field_headers(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteEnrollmentRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_enrollment(request) - response = client.delete_channel_connection(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_delete_channel_connection_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_delete_enrollment_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.delete_channel_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteEnrollmentRequest() + request.name = "name_value" -def test_delete_channel_connection_rest_flattened(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_enrollment_flattened(): client = EventarcClient( 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/channelConnections/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_enrollment( name="name_value", + etag="etag_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_channel_connection(**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/v1/{name=projects/*/locations/*/channelConnections/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].etag + mock_val = "etag_value" + assert arg == mock_val -def test_delete_channel_connection_rest_flattened_error(transport: str = "rest"): +def test_delete_enrollment_flattened_error(): client = EventarcClient( 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_channel_connection( - eventarc.DeleteChannelConnectionRequest(), + client.delete_enrollment( + eventarc.DeleteEnrollmentRequest(), name="name_value", + etag="etag_value", ) -def test_get_google_channel_config_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 = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_delete_enrollment_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Ensure method has been cached - assert ( - client._transport.get_google_channel_config - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - - # 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. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_enrollment( + name="name_value", + etag="etag_value", ) - client._transport._wrapped_methods[ - client._transport.get_google_channel_config - ] = mock_rpc - - request = {} - client.get_google_channel_config(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].etag + mock_val = "etag_value" + assert arg == mock_val - client.get_google_channel_config(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_delete_enrollment_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_enrollment( + eventarc.DeleteEnrollmentRequest(), + name="name_value", + etag="etag_value", + ) -def test_get_google_channel_config_rest_required_fields( - request_type=eventarc.GetGoogleChannelConfigRequest, -): - transport_class = transports.EventarcRestTransport - - request_init = {} - request_init["name"] = "" - 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_google_channel_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_google_channel_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetPipelineRequest, + dict, + ], +) +def test_get_pipeline(request_type, transport: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = google_channel_config.GoogleChannelConfig() - # 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 = google_channel_config.GoogleChannelConfig.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 - - response = client.get_google_channel_config(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = pipeline.Pipeline( + name="name_value", + uid="uid_value", + display_name="display_name_value", + crypto_key_name="crypto_key_name_value", + etag="etag_value", + ) + response = client.get_pipeline(request) -def test_get_google_channel_config_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetPipelineRequest() + assert args[0] == request - unset_fields = transport.get_google_channel_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Establish that the response is the type that we expect. + assert isinstance(response, pipeline.Pipeline) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.display_name == "display_name_value" + assert response.crypto_key_name == "crypto_key_name_value" + assert response.etag == "etag_value" -def test_get_google_channel_config_rest_flattened(): +def test_get_pipeline_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # 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 = google_channel_config.GoogleChannelConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/googleChannelConfig" - } + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.GetPipelineRequest( + name="name_value", + ) - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_pipeline(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetPipelineRequest( name="name_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = google_channel_config.GoogleChannelConfig.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 - client.get_google_channel_config(**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/v1/{name=projects/*/locations/*/googleChannelConfig}" - % client.transport._host, - args[1], +def test_get_pipeline_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_get_google_channel_config_rest_flattened_error(transport: str = "rest"): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Ensure method has been cached + assert client._transport.get_pipeline in client._transport._wrapped_methods - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_google_channel_config( - eventarc.GetGoogleChannelConfigRequest(), - name="name_value", + # 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_pipeline] = mock_rpc + request = {} + client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_pipeline(request) -def test_update_google_channel_config_rest_use_cached_wrapped_rpc(): + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_pipeline_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -11655,1206 +12685,17301 @@ def test_update_google_channel_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_google_channel_config - in client._transport._wrapped_methods + client._client._transport.get_pipeline + in client._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_google_channel_config + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_pipeline ] = mock_rpc request = {} - client.update_google_channel_config(request) + await client.get_pipeline(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_google_channel_config(request) + await client.get_pipeline(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_google_channel_config_rest_required_fields( - request_type=eventarc.UpdateGoogleChannelConfigRequest, +@pytest.mark.asyncio +async def test_get_pipeline_async( + transport: str = "grpc_asyncio", request_type=eventarc.GetPipelineRequest ): - transport_class = transports.EventarcRestTransport - - 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) + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_google_channel_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + pipeline.Pipeline( + name="name_value", + uid="uid_value", + display_name="display_name_value", + crypto_key_name="crypto_key_name_value", + etag="etag_value", + ) + ) + response = await client.get_pipeline(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetPipelineRequest() + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_google_channel_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) - jsonified_request.update(unset_fields) + # Establish that the response is the type that we expect. + assert isinstance(response, pipeline.Pipeline) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.display_name == "display_name_value" + assert response.crypto_key_name == "crypto_key_name_value" + assert response.etag == "etag_value" - # verify required fields with non-default values are left alone +@pytest.mark.asyncio +async def test_get_pipeline_async_from_dict(): + await test_get_pipeline_async(request_type=dict) + + +def test_get_pipeline_field_headers(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = gce_google_channel_config.GoogleChannelConfig() - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetPipelineRequest() - # Convert return value to protobuf type - return_value = gce_google_channel_config.GoogleChannelConfig.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + call.return_value = pipeline.Pipeline() + client.get_pipeline(request) - response = client.update_google_channel_config(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_update_google_channel_config_rest_unset_required_fields(): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_pipeline_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.update_google_channel_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("googleChannelConfig",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetPipelineRequest() + request.name = "name_value" -def test_update_google_channel_config_rest_flattened(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline()) + await client.get_pipeline(request) - # 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 = gce_google_channel_config.GoogleChannelConfig() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - # get arguments that satisfy an http rule for this method - sample_request = { - "google_channel_config": { - "name": "projects/sample1/locations/sample2/googleChannelConfig" - } - } + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - # get truthy value for each flattened field - mock_args = dict( - google_channel_config=gce_google_channel_config.GoogleChannelConfig( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = gce_google_channel_config.GoogleChannelConfig.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 +def test_get_pipeline_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - client.update_google_channel_config(**mock_args) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = pipeline.Pipeline() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_pipeline( + name="name_value", + ) # 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/v1/{google_channel_config.name=projects/*/locations/*/googleChannelConfig}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_update_google_channel_config_rest_flattened_error(transport: str = "rest"): +def test_get_pipeline_flattened_error(): client = EventarcClient( 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_google_channel_config( - eventarc.UpdateGoogleChannelConfigRequest(), - google_channel_config=gce_google_channel_config.GoogleChannelConfig( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_pipeline( + eventarc.GetPipelineRequest(), + name="name_value", ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.asyncio +async def test_get_pipeline_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - with pytest.raises(ValueError): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EventarcClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = pipeline.Pipeline() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(pipeline.Pipeline()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_pipeline( + name="name_value", ) - # It is an error to provide an api_key and a transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_pipeline_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EventarcClient( - 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" + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): - client = EventarcClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + await client.get_pipeline( + eventarc.GetPipelineRequest(), + name="name_value", ) - # It is an error to provide scopes and a transport instance. - transport = transports.EventarcGrpcTransport( + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListPipelinesRequest, + dict, + ], +) +def test_list_pipelines(request_type, transport: str = "grpc"): + client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = EventarcClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListPipelinesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) + response = client.list_pipelines(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListPipelinesRequest() + assert args[0] == request -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EventarcGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EventarcClient(transport=transport) - assert client.transport is transport + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPipelinesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EventarcGrpcTransport( +def test_list_pipelines_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - channel = transport.grpc_channel - assert channel - transport = transports.EventarcGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.ListPipelinesRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_pipelines(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListPipelinesRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EventarcGrpcTransport, - transports.EventarcGrpcAsyncIOTransport, - transports.EventarcRestTransport, - ], -) -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_list_pipelines_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -def test_transport_kind_grpc(): - transport = EventarcClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + # Ensure method has been cached + assert client._transport.list_pipelines in client._transport._wrapped_methods -def test_initialize_client_w_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # 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_pipelines] = mock_rpc + request = {} + client.list_pipelines(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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_trigger_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.list_pipelines(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_trigger), "__call__") as call: - call.return_value = trigger.Trigger() - client.get_trigger(request=None) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetTriggerRequest() - assert args[0] == request_msg +@pytest.mark.asyncio +async def test_list_pipelines_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_triggers_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert ( + client._client._transport.list_pipelines + in client._client._transport._wrapped_methods + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_triggers), "__call__") as call: - call.return_value = eventarc.ListTriggersResponse() - client.list_triggers(request=None) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_pipelines + ] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListTriggersRequest() + request = {} + await client.list_pipelines(request) - assert args[0] == request_msg + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + await client.list_pipelines(request) -# 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_create_trigger_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_pipelines_async( + transport: str = "grpc_asyncio", request_type=eventarc.ListPipelinesRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_trigger), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_trigger(request=None) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Establish that the underlying stub method was called. - call.assert_called() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListPipelinesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateTriggerRequest() + request = eventarc.ListPipelinesRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPipelinesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -# 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_trigger_empty_call_grpc(): +@pytest.mark.asyncio +async def test_list_pipelines_async_from_dict(): + await test_list_pipelines_async(request_type=dict) + + +def test_list_pipelines_field_headers(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_trigger), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_trigger(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListPipelinesRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + call.return_value = eventarc.ListPipelinesResponse() + client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateTriggerRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -# 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_trigger_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_pipelines_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_trigger), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_trigger(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListPipelinesRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListPipelinesResponse() + ) + await client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteTriggerRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -# 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_channel_empty_call_grpc(): +def test_list_pipelines_flattened(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_channel), "__call__") as call: - call.return_value = channel.Channel() - client.get_channel(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListPipelinesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_pipelines( + parent="parent_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelRequest() - - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -# 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_channels_empty_call_grpc(): +def test_list_pipelines_flattened_error(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_channels), "__call__") as call: - call.return_value = eventarc.ListChannelsResponse() - client.list_channels(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_pipelines( + eventarc.ListPipelinesRequest(), + parent="parent_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelsRequest() - assert args[0] == request_msg +@pytest.mark.asyncio +async def test_list_pipelines_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListPipelinesResponse() -# 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_create_channel_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_channel(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListPipelinesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_pipelines( + parent="parent_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelRequest() - - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -# 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_channel_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_pipelines_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_channel(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateChannelRequest() - - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_pipelines( + eventarc.ListPipelinesRequest(), + parent="parent_value", + ) -# 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_channel_empty_call_grpc(): +def test_list_pipelines_pager(transport_name: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_channel(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token="abc", + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token="def", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token="ghi", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + RuntimeError, + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelRequest() + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_pipelines(request={}, retry=retry, timeout=timeout) - assert args[0] == request_msg + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, pipeline.Pipeline) for i in results) -# 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_provider_empty_call_grpc(): + +def test_list_pipelines_pages(transport_name: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_provider), "__call__") as call: - call.return_value = discovery.Provider() - client.get_provider(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token="abc", + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token="def", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token="ghi", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + RuntimeError, + ) + pages = list(client.list_pipelines(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetProviderRequest() - assert args[0] == request_msg +@pytest.mark.asyncio +async def test_list_pipelines_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token="abc", + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token="def", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token="ghi", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_pipelines( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) -# 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_providers_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + assert len(responses) == 6 + assert all(isinstance(i, pipeline.Pipeline) for i in responses) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_providers), "__call__") as call: - call.return_value = eventarc.ListProvidersResponse() - client.list_providers(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListProvidersRequest() +@pytest.mark.asyncio +async def test_list_pipelines_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) - assert args[0] == request_msg + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pipelines), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token="abc", + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token="def", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token="ghi", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_pipelines(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_channel_connection_empty_call_grpc(): +@pytest.mark.parametrize( + "request_type", + [ + eventarc.CreatePipelineRequest, + dict, + ], +) +def test_create_pipeline(request_type, transport: str = "grpc"): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), "__call__" - ) as call: - call.return_value = channel_connection.ChannelConnection() - client.get_channel_connection(request=None) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Establish that the underlying stub method was called. - call.assert_called() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelConnectionRequest() + request = eventarc.CreatePipelineRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# 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_channel_connections_empty_call_grpc(): +def test_create_pipeline_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), "__call__" - ) as call: - call.return_value = eventarc.ListChannelConnectionsResponse() - client.list_channel_connections(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.CreatePipelineRequest( + parent="parent_value", + pipeline_id="pipeline_id_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_pipeline(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelConnectionsRequest() + assert args[0] == eventarc.CreatePipelineRequest( + parent="parent_value", + pipeline_id="pipeline_id_value", + ) - assert args[0] == request_msg +def test_create_pipeline_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -# 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_create_channel_connection_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_channel_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelConnectionRequest() - - 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_channel_connection_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_channel_connection(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelConnectionRequest() + # Ensure method has been cached + assert client._transport.create_pipeline in client._transport._wrapped_methods - assert args[0] == request_msg + # 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.create_pipeline] = mock_rpc + request = {} + client.create_pipeline(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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_google_channel_config_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), "__call__" - ) as call: - call.return_value = google_channel_config.GoogleChannelConfig() - client.get_google_channel_config(request=None) + client.create_pipeline(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleChannelConfigRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - assert args[0] == request_msg +@pytest.mark.asyncio +async def test_create_pipeline_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) -# 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_google_channel_config_empty_call_grpc(): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_google_channel_config), "__call__" - ) as call: - call.return_value = gce_google_channel_config.GoogleChannelConfig() - client.update_google_channel_config(request=None) + # Ensure method has been cached + assert ( + client._client._transport.create_pipeline + in client._client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleChannelConfigRequest() + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_pipeline + ] = mock_rpc - assert args[0] == request_msg + request = {} + await client.create_pipeline(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_transport_kind_grpc_asyncio(): - transport = EventarcAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + await client.create_pipeline(request) -def test_initialize_client_w_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_trigger_empty_call_grpc_asyncio(): +async def test_create_pipeline_async( + transport: str = "grpc_asyncio", request_type=eventarc.CreatePipelineRequest +): client = EventarcAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_trigger), "__call__") as call: + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - trigger.Trigger( - name="name_value", - uid="uid_value", - service_account="service_account_value", - channel="channel_value", - etag="etag_value", - ) + operations_pb2.Operation(name="operations/spam") ) - await client.get_trigger(request=None) + response = await client.create_pipeline(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetTriggerRequest() + request = eventarc.CreatePipelineRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_triggers_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +async def test_create_pipeline_async_from_dict(): + await test_create_pipeline_async(request_type=dict) + + +def test_create_pipeline_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_triggers), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - eventarc.ListTriggersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_triggers(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreatePipelineRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListTriggersRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_create_trigger_empty_call_grpc_asyncio(): +async def test_create_pipeline_field_headers_async(): client = EventarcAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_trigger), "__call__") as call: - # Designate an appropriate return value for the call. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreatePipelineRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name="operations/op") ) - await client.create_trigger(request=None) + await client.create_pipeline(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateTriggerRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_trigger_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_pipeline_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_trigger), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_pipeline( + parent="parent_value", + pipeline=gce_pipeline.Pipeline(name="name_value"), + pipeline_id="pipeline_id_value", ) - await client.update_trigger(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateTriggerRequest() + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].pipeline + mock_val = gce_pipeline.Pipeline(name="name_value") + assert arg == mock_val + arg = args[0].pipeline_id + mock_val = "pipeline_id_value" + assert arg == mock_val - assert args[0] == request_msg + +def test_create_pipeline_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_pipeline( + eventarc.CreatePipelineRequest(), + parent="parent_value", + pipeline=gce_pipeline.Pipeline(name="name_value"), + pipeline_id="pipeline_id_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_delete_trigger_empty_call_grpc_asyncio(): +async def test_create_pipeline_flattened_async(): client = EventarcAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_trigger), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - await client.delete_trigger(request=None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_pipeline( + parent="parent_value", + pipeline=gce_pipeline.Pipeline(name="name_value"), + pipeline_id="pipeline_id_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteTriggerRequest() - - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].pipeline + mock_val = gce_pipeline.Pipeline(name="name_value") + assert arg == mock_val + arg = args[0].pipeline_id + mock_val = "pipeline_id_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_channel_empty_call_grpc_asyncio(): +async def test_create_pipeline_flattened_error_async(): client = EventarcAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_channel), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - channel.Channel( - name="name_value", - uid="uid_value", - provider="provider_value", - state=channel.Channel.State.PENDING, - activation_token="activation_token_value", - crypto_key_name="crypto_key_name_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_pipeline( + eventarc.CreatePipelineRequest(), + parent="parent_value", + pipeline=gce_pipeline.Pipeline(name="name_value"), + pipeline_id="pipeline_id_value", ) - await client.get_channel(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.UpdatePipelineRequest, + dict, + ], +) +def test_update_pipeline(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelRequest() + request = eventarc.UpdatePipelineRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_channels_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_pipeline_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_channels), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - eventarc.ListChannelsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_channels(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.UpdatePipelineRequest() - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_pipeline(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelsRequest() + assert args[0] == eventarc.UpdatePipelineRequest() - assert args[0] == request_msg +def test_update_pipeline_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_channel_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Ensure method has been cached + assert client._transport.update_pipeline 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. ) - await client.create_channel(request=None) + client._transport._wrapped_methods[client._transport.update_pipeline] = mock_rpc + request = {} + client.update_pipeline(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelRequest() + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - assert args[0] == request_msg + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_pipeline(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_update_channel_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) +async def test_update_pipeline_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_channel), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_pipeline + in client._client._transport._wrapped_methods ) - await client.update_channel(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateChannelRequest() + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_pipeline + ] = mock_rpc - assert args[0] == request_msg + request = {} + await client.update_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_pipeline(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_delete_channel_empty_call_grpc_asyncio(): +async def test_update_pipeline_async( + transport: str = "grpc_asyncio", request_type=eventarc.UpdatePipelineRequest +): client = EventarcAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - await client.delete_channel(request=None) + response = await client.update_pipeline(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelRequest() + request = eventarc.UpdatePipelineRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_provider_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +async def test_update_pipeline_async_from_dict(): + await test_update_pipeline_async(request_type=dict) + + +def test_update_pipeline_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_provider), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - discovery.Provider( - name="name_value", - display_name="display_name_value", - ) - ) - await client.get_provider(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdatePipelineRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.pipeline.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetProviderRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "pipeline.name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_providers_empty_call_grpc_asyncio(): +async def test_update_pipeline_field_headers_async(): client = EventarcAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_providers), "__call__") as call: - # Designate an appropriate return value for the call. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdatePipelineRequest() + + request.pipeline.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - eventarc.ListProvidersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/op") ) - await client.list_providers(request=None) + await client.update_pipeline(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListProvidersRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "pipeline.name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_channel_connection_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_pipeline_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), "__call__" - ) as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - channel_connection.ChannelConnection( - name="name_value", - uid="uid_value", - channel="channel_value", - activation_token="activation_token_value", - ) + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_pipeline( + pipeline=gce_pipeline.Pipeline(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.get_channel_connection(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelConnectionRequest() + arg = args[0].pipeline + mock_val = gce_pipeline.Pipeline(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val - assert args[0] == request_msg + +def test_update_pipeline_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_pipeline( + eventarc.UpdatePipelineRequest(), + pipeline=gce_pipeline.Pipeline(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_channel_connections_empty_call_grpc_asyncio(): +async def test_update_pipeline_flattened_async(): client = EventarcAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_channel_connections), "__call__" - ) as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - eventarc.ListChannelConnectionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_pipeline( + pipeline=gce_pipeline.Pipeline(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.list_channel_connections(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelConnectionsRequest() - - assert args[0] == request_msg + arg = args[0].pipeline + mock_val = gce_pipeline.Pipeline(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_create_channel_connection_empty_call_grpc_asyncio(): +async def test_update_pipeline_flattened_error_async(): client = EventarcAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_channel_connection), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_pipeline( + eventarc.UpdatePipelineRequest(), + pipeline=gce_pipeline.Pipeline(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.create_channel_connection(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.DeletePipelineRequest, + dict, + ], +) +def test_delete_pipeline(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelConnectionRequest() + request = eventarc.DeletePipelineRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_channel_connection_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_pipeline_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_channel_connection), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.delete_channel_connection(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.DeletePipelineRequest( + name="name_value", + etag="etag_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_pipeline(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelConnectionRequest() + assert args[0] == eventarc.DeletePipelineRequest( + name="name_value", + etag="etag_value", + ) - assert args[0] == request_msg + +def test_delete_pipeline_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_pipeline 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_pipeline] = mock_rpc + request = {} + client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_pipeline(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_pipeline_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_pipeline + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_pipeline + ] = mock_rpc + + request = {} + await client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_pipeline(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_pipeline_async( + transport: str = "grpc_asyncio", request_type=eventarc.DeletePipelineRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeletePipelineRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_pipeline_async_from_dict(): + await test_delete_pipeline_async(request_type=dict) + + +def test_delete_pipeline_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeletePipelineRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_pipeline_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeletePipelineRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_pipeline_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_pipeline( + name="name_value", + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].etag + mock_val = "etag_value" + assert arg == mock_val + + +def test_delete_pipeline_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_pipeline( + eventarc.DeletePipelineRequest(), + name="name_value", + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_delete_pipeline_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_pipeline( + name="name_value", + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].etag + mock_val = "etag_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_pipeline_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_pipeline( + eventarc.DeletePipelineRequest(), + name="name_value", + etag="etag_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetGoogleApiSourceRequest, + dict, + ], +) +def test_get_google_api_source(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = google_api_source.GoogleApiSource( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + destination="destination_value", + crypto_key_name="crypto_key_name_value", + ) + response = client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.GetGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, google_api_source.GoogleApiSource) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.destination == "destination_value" + assert response.crypto_key_name == "crypto_key_name_value" + + +def test_get_google_api_source_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.GetGoogleApiSourceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_google_api_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.GetGoogleApiSourceRequest( + name="name_value", + ) + + +def test_get_google_api_source_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_google_api_source + 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_google_api_source + ] = mock_rpc + request = {} + client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_api_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_google_api_source_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_google_api_source + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_google_api_source + ] = mock_rpc + + request = {} + await client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_google_api_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_google_api_source_async( + transport: str = "grpc_asyncio", request_type=eventarc.GetGoogleApiSourceRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + google_api_source.GoogleApiSource( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + destination="destination_value", + crypto_key_name="crypto_key_name_value", + ) + ) + response = await client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.GetGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, google_api_source.GoogleApiSource) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.destination == "destination_value" + assert response.crypto_key_name == "crypto_key_name_value" + + +@pytest.mark.asyncio +async def test_get_google_api_source_async_from_dict(): + await test_get_google_api_source_async(request_type=dict) + + +def test_get_google_api_source_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetGoogleApiSourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + call.return_value = google_api_source.GoogleApiSource() + client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_google_api_source_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.GetGoogleApiSourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + google_api_source.GoogleApiSource() + ) + await client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_google_api_source_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = google_api_source.GoogleApiSource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_google_api_source( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_google_api_source_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_google_api_source( + eventarc.GetGoogleApiSourceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_google_api_source_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = google_api_source.GoogleApiSource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + google_api_source.GoogleApiSource() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_google_api_source( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_google_api_source_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_google_api_source( + eventarc.GetGoogleApiSourceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListGoogleApiSourcesRequest, + dict, + ], +) +def test_list_google_api_sources(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListGoogleApiSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.ListGoogleApiSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleApiSourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_google_api_sources_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.ListGoogleApiSourcesRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_google_api_sources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.ListGoogleApiSourcesRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", + ) + + +def test_list_google_api_sources_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_google_api_sources + 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_google_api_sources + ] = mock_rpc + request = {} + client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_google_api_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_google_api_sources_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_google_api_sources + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_google_api_sources + ] = mock_rpc + + request = {} + await client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_google_api_sources(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_google_api_sources_async( + transport: str = "grpc_asyncio", request_type=eventarc.ListGoogleApiSourcesRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListGoogleApiSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.ListGoogleApiSourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleApiSourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_google_api_sources_async_from_dict(): + await test_list_google_api_sources_async(request_type=dict) + + +def test_list_google_api_sources_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListGoogleApiSourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + call.return_value = eventarc.ListGoogleApiSourcesResponse() + client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_google_api_sources_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.ListGoogleApiSourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListGoogleApiSourcesResponse() + ) + await client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_google_api_sources_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListGoogleApiSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_google_api_sources( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_google_api_sources_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_google_api_sources( + eventarc.ListGoogleApiSourcesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_google_api_sources_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = eventarc.ListGoogleApiSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListGoogleApiSourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_google_api_sources( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_google_api_sources_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_google_api_sources( + eventarc.ListGoogleApiSourcesRequest(), + parent="parent_value", + ) + + +def test_list_google_api_sources_pager(transport_name: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token="abc", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token="def", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token="ghi", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_google_api_sources(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, google_api_source.GoogleApiSource) for i in results) + + +def test_list_google_api_sources_pages(transport_name: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token="abc", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token="def", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token="ghi", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_google_api_sources(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_google_api_sources_async_pager(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token="abc", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token="def", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token="ghi", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_google_api_sources( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, google_api_source.GoogleApiSource) for i in responses) + + +@pytest.mark.asyncio +async def test_list_google_api_sources_async_pages(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token="abc", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token="def", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token="ghi", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_google_api_sources(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.CreateGoogleApiSourceRequest, + dict, + ], +) +def test_create_google_api_source(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.CreateGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_google_api_source_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source_id="google_api_source_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_google_api_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.CreateGoogleApiSourceRequest( + parent="parent_value", + google_api_source_id="google_api_source_id_value", + ) + + +def test_create_google_api_source_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_google_api_source + 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.create_google_api_source + ] = mock_rpc + request = {} + client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_google_api_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_google_api_source_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_google_api_source + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_google_api_source + ] = mock_rpc + + request = {} + await client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_google_api_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_google_api_source_async( + transport: str = "grpc_asyncio", request_type=eventarc.CreateGoogleApiSourceRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.CreateGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_google_api_source_async_from_dict(): + await test_create_google_api_source_async(request_type=dict) + + +def test_create_google_api_source_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateGoogleApiSourceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_google_api_source_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.CreateGoogleApiSourceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_google_api_source_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_google_api_source( + parent="parent_value", + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + google_api_source_id="google_api_source_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].google_api_source + mock_val = gce_google_api_source.GoogleApiSource(name="name_value") + assert arg == mock_val + arg = args[0].google_api_source_id + mock_val = "google_api_source_id_value" + assert arg == mock_val + + +def test_create_google_api_source_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_google_api_source( + eventarc.CreateGoogleApiSourceRequest(), + parent="parent_value", + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + google_api_source_id="google_api_source_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_google_api_source_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_google_api_source( + parent="parent_value", + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + google_api_source_id="google_api_source_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].google_api_source + mock_val = gce_google_api_source.GoogleApiSource(name="name_value") + assert arg == mock_val + arg = args[0].google_api_source_id + mock_val = "google_api_source_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_google_api_source_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_google_api_source( + eventarc.CreateGoogleApiSourceRequest(), + parent="parent_value", + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + google_api_source_id="google_api_source_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.UpdateGoogleApiSourceRequest, + dict, + ], +) +def test_update_google_api_source(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_google_api_source_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.UpdateGoogleApiSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_google_api_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.UpdateGoogleApiSourceRequest() + + +def test_update_google_api_source_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_google_api_source + 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_google_api_source + ] = mock_rpc + request = {} + client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_google_api_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_google_api_source_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_google_api_source + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_google_api_source + ] = mock_rpc + + request = {} + await client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_google_api_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_google_api_source_async( + transport: str = "grpc_asyncio", request_type=eventarc.UpdateGoogleApiSourceRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.UpdateGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_google_api_source_async_from_dict(): + await test_update_google_api_source_async(request_type=dict) + + +def test_update_google_api_source_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateGoogleApiSourceRequest() + + request.google_api_source.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "google_api_source.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_google_api_source_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.UpdateGoogleApiSourceRequest() + + request.google_api_source.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "google_api_source.name=name_value", + ) in kw["metadata"] + + +def test_update_google_api_source_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_google_api_source( + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].google_api_source + mock_val = gce_google_api_source.GoogleApiSource(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_google_api_source_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_google_api_source( + eventarc.UpdateGoogleApiSourceRequest(), + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_google_api_source_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_google_api_source( + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].google_api_source + mock_val = gce_google_api_source.GoogleApiSource(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_google_api_source_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_google_api_source( + eventarc.UpdateGoogleApiSourceRequest(), + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.DeleteGoogleApiSourceRequest, + dict, + ], +) +def test_delete_google_api_source(request_type, transport: str = "grpc"): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_google_api_source_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = eventarc.DeleteGoogleApiSourceRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_google_api_source(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == eventarc.DeleteGoogleApiSourceRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_google_api_source_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 = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_google_api_source + 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_google_api_source + ] = mock_rpc + request = {} + client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_google_api_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_google_api_source_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_google_api_source + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_google_api_source + ] = mock_rpc + + request = {} + await client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_google_api_source(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_google_api_source_async( + transport: str = "grpc_asyncio", request_type=eventarc.DeleteGoogleApiSourceRequest +): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = eventarc.DeleteGoogleApiSourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_google_api_source_async_from_dict(): + await test_delete_google_api_source_async(request_type=dict) + + +def test_delete_google_api_source_field_headers(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteGoogleApiSourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_google_api_source_field_headers_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = eventarc.DeleteGoogleApiSourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_google_api_source_flattened(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_google_api_source( + name="name_value", + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].etag + mock_val = "etag_value" + assert arg == mock_val + + +def test_delete_google_api_source_flattened_error(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_google_api_source( + eventarc.DeleteGoogleApiSourceRequest(), + name="name_value", + etag="etag_value", + ) + + +@pytest.mark.asyncio +async def test_delete_google_api_source_flattened_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_google_api_source( + name="name_value", + etag="etag_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].etag + mock_val = "etag_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_google_api_source_flattened_error_async(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_google_api_source( + eventarc.DeleteGoogleApiSourceRequest(), + name="name_value", + etag="etag_value", + ) + + +def test_get_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + client.get_trigger(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_trigger(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_trigger_rest_required_fields(request_type=eventarc.GetTriggerRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_trigger._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_trigger._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = trigger.Trigger() + # 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 = trigger.Trigger.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 + + response = client.get_trigger(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_trigger_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_trigger_rest_flattened(): + client = EventarcClient( + 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 = trigger.Trigger() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/triggers/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = trigger.Trigger.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 + + client.get_trigger(**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/v1/{name=projects/*/locations/*/triggers/*}" % client.transport._host, + args[1], + ) + + +def test_get_trigger_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_trigger( + eventarc.GetTriggerRequest(), + name="name_value", + ) + + +def test_list_triggers_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 = EventarcClient( + 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_triggers 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_triggers] = mock_rpc + + request = {} + client.list_triggers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_triggers(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_triggers_rest_required_fields(request_type=eventarc.ListTriggersRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_triggers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_triggers._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListTriggersResponse() + # 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 = eventarc.ListTriggersResponse.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 + + response = client.list_triggers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_triggers_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_triggers._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_triggers_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListTriggersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListTriggersResponse.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 + + client.list_triggers(**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/v1/{parent=projects/*/locations/*}/triggers" % client.transport._host, + args[1], + ) + + +def test_list_triggers_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_triggers( + eventarc.ListTriggersRequest(), + parent="parent_value", + ) + + +def test_list_triggers_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + trigger.Trigger(), + ], + next_page_token="abc", + ), + eventarc.ListTriggersResponse( + triggers=[], + next_page_token="def", + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + ], + next_page_token="ghi", + ), + eventarc.ListTriggersResponse( + triggers=[ + trigger.Trigger(), + trigger.Trigger(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListTriggersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_triggers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, trigger.Trigger) for i in results) + + pages = list(client.list_triggers(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_trigger_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 = EventarcClient( + 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.create_trigger 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.create_trigger] = mock_rpc + + request = {} + client.create_trigger(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.create_trigger(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_create_trigger_rest_required_fields( + request_type=eventarc.CreateTriggerRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["trigger_id"] = "" + 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 + assert "triggerId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_trigger._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "triggerId" in jsonified_request + assert jsonified_request["triggerId"] == request_init["trigger_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["triggerId"] = "trigger_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_trigger._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "trigger_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "triggerId" in jsonified_request + assert jsonified_request["triggerId"] == "trigger_id_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_trigger(request) + + expected_params = [ + ( + "triggerId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_trigger_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_trigger._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "triggerId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "trigger", + "triggerId", + ) + ) + ) + + +def test_create_trigger_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + trigger=gce_trigger.Trigger(name="name_value"), + trigger_id="trigger_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_trigger(**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/v1/{parent=projects/*/locations/*}/triggers" % client.transport._host, + args[1], + ) + + +def test_create_trigger_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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.create_trigger( + eventarc.CreateTriggerRequest(), + parent="parent_value", + trigger=gce_trigger.Trigger(name="name_value"), + trigger_id="trigger_id_value", + ) + + +def test_update_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + client.update_trigger(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_trigger(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_trigger_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "trigger": {"name": "projects/sample1/locations/sample2/triggers/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + trigger=gce_trigger.Trigger(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + allow_missing=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_trigger(**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/v1/{trigger.name=projects/*/locations/*/triggers/*}" + % client.transport._host, + args[1], + ) + + +def test_update_trigger_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_trigger( + eventarc.UpdateTriggerRequest(), + trigger=gce_trigger.Trigger(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + allow_missing=True, + ) + + +def test_delete_trigger_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 = EventarcClient( + 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_trigger 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_trigger] = mock_rpc + + request = {} + client.delete_trigger(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_trigger(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_trigger_rest_required_fields( + request_type=eventarc.DeleteTriggerRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_trigger._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_trigger._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "etag", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_trigger(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_trigger_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_trigger._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +def test_delete_trigger_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/triggers/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + allow_missing=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_trigger(**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/v1/{name=projects/*/locations/*/triggers/*}" % client.transport._host, + args[1], + ) + + +def test_delete_trigger_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_trigger( + eventarc.DeleteTriggerRequest(), + name="name_value", + allow_missing=True, + ) + + +def test_get_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + + request = {} + client.get_channel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel(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_channel_rest_required_fields(request_type=eventarc.GetChannelRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_channel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_channel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = channel.Channel() + # 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 = channel.Channel.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 + + response = client.get_channel(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_channel_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_channel_rest_flattened(): + client = EventarcClient( + 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 = channel.Channel() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = channel.Channel.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 + + client.get_channel(**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/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, + args[1], + ) + + +def test_get_channel_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_channel( + eventarc.GetChannelRequest(), + name="name_value", + ) + + +def test_list_channels_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 = EventarcClient( + 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_channels 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_channels] = mock_rpc + + request = {} + client.list_channels(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_channels(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_channels_rest_required_fields(request_type=eventarc.ListChannelsRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_channels._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_channels._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListChannelsResponse() + # 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 = eventarc.ListChannelsResponse.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 + + response = client.list_channels(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_channels_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_channels._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_channels_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListChannelsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListChannelsResponse.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 + + client.list_channels(**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/v1/{parent=projects/*/locations/*}/channels" % client.transport._host, + args[1], + ) + + +def test_list_channels_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_channels( + eventarc.ListChannelsRequest(), + parent="parent_value", + ) + + +def test_list_channels_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + channel.Channel(), + ], + next_page_token="abc", + ), + eventarc.ListChannelsResponse( + channels=[], + next_page_token="def", + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + ], + next_page_token="ghi", + ), + eventarc.ListChannelsResponse( + channels=[ + channel.Channel(), + channel.Channel(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListChannelsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_channels(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, channel.Channel) for i in results) + + pages = list(client.list_channels(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_channel_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 = EventarcClient( + 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.create_channel_ 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.create_channel_] = mock_rpc + + request = {} + client.create_channel(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.create_channel(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_create_channel_rest_required_fields( + request_type=eventarc.CreateChannelRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["channel_id"] = "" + 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 + assert "channelId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_channel_._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == request_init["channel_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["channelId"] = "channel_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_channel_._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "channel_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "channelId" in jsonified_request + assert jsonified_request["channelId"] == "channel_id_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_channel(request) + + expected_params = [ + ( + "channelId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_channel_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_channel_._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "channelId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "channel", + "channelId", + ) + ) + ) + + +def test_create_channel_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + channel=gce_channel.Channel(name="name_value"), + channel_id="channel_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_channel(**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/v1/{parent=projects/*/locations/*}/channels" % client.transport._host, + args[1], + ) + + +def test_create_channel_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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.create_channel( + eventarc.CreateChannelRequest(), + parent="parent_value", + channel=gce_channel.Channel(name="name_value"), + channel_id="channel_id_value", + ) + + +def test_update_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + + request = {} + client.update_channel(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_channel(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_channel_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + channel=gce_channel.Channel(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_channel(**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/v1/{channel.name=projects/*/locations/*/channels/*}" + % client.transport._host, + args[1], + ) + + +def test_update_channel_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_channel( + eventarc.UpdateChannelRequest(), + channel=gce_channel.Channel(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_channel_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 = EventarcClient( + 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_channel 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_channel] = mock_rpc + + request = {} + client.delete_channel(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_channel(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_channel_rest_required_fields( + request_type=eventarc.DeleteChannelRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_channel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_channel._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_channel(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_channel_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_channel._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly",)) & set(("name",))) + + +def test_delete_channel_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/channels/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_channel(**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/v1/{name=projects/*/locations/*/channels/*}" % client.transport._host, + args[1], + ) + + +def test_delete_channel_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_channel( + eventarc.DeleteChannelRequest(), + name="name_value", + ) + + +def test_get_provider_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 = EventarcClient( + 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_provider 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_provider] = mock_rpc + + request = {} + client.get_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_provider(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_provider_rest_required_fields(request_type=eventarc.GetProviderRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_provider._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_provider._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = discovery.Provider() + # 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 = discovery.Provider.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 + + response = client.get_provider(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_provider_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_provider._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_provider_rest_flattened(): + client = EventarcClient( + 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 = discovery.Provider() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/providers/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = discovery.Provider.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 + + client.get_provider(**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/v1/{name=projects/*/locations/*/providers/*}" % client.transport._host, + args[1], + ) + + +def test_get_provider_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_provider( + eventarc.GetProviderRequest(), + name="name_value", + ) + + +def test_list_providers_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 = EventarcClient( + 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_providers 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_providers] = mock_rpc + + request = {} + client.list_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_providers(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_providers_rest_required_fields( + request_type=eventarc.ListProvidersRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_providers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_providers._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListProvidersResponse() + # 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 = eventarc.ListProvidersResponse.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 + + response = client.list_providers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_providers_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_providers._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_providers_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListProvidersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListProvidersResponse.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 + + client.list_providers(**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/v1/{parent=projects/*/locations/*}/providers" % client.transport._host, + args[1], + ) + + +def test_list_providers_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_providers( + eventarc.ListProvidersRequest(), + parent="parent_value", + ) + + +def test_list_providers_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + discovery.Provider(), + ], + next_page_token="abc", + ), + eventarc.ListProvidersResponse( + providers=[], + next_page_token="def", + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + ], + next_page_token="ghi", + ), + eventarc.ListProvidersResponse( + providers=[ + discovery.Provider(), + discovery.Provider(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListProvidersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_providers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, discovery.Provider) for i in results) + + pages = list(client.list_providers(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_channel_connection_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 = EventarcClient( + 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_channel_connection + 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_channel_connection + ] = mock_rpc + + request = {} + client.get_channel_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel_connection(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_channel_connection_rest_required_fields( + request_type=eventarc.GetChannelConnectionRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_channel_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_channel_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = channel_connection.ChannelConnection() + # 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 = channel_connection.ChannelConnection.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 + + response = client.get_channel_connection(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_channel_connection_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_channel_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_channel_connection_rest_flattened(): + client = EventarcClient( + 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 = channel_connection.ChannelConnection() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/channelConnections/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = channel_connection.ChannelConnection.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 + + client.get_channel_connection(**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/v1/{name=projects/*/locations/*/channelConnections/*}" + % client.transport._host, + args[1], + ) + + +def test_get_channel_connection_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_channel_connection( + eventarc.GetChannelConnectionRequest(), + name="name_value", + ) + + +def test_list_channel_connections_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 = EventarcClient( + 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_channel_connections + 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_channel_connections + ] = mock_rpc + + request = {} + client.list_channel_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_channel_connections(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_channel_connections_rest_required_fields( + request_type=eventarc.ListChannelConnectionsRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_channel_connections._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_channel_connections._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListChannelConnectionsResponse() + # 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 = eventarc.ListChannelConnectionsResponse.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 + + response = client.list_channel_connections(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_channel_connections_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_channel_connections._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_channel_connections_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListChannelConnectionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListChannelConnectionsResponse.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 + + client.list_channel_connections(**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/v1/{parent=projects/*/locations/*}/channelConnections" + % client.transport._host, + args[1], + ) + + +def test_list_channel_connections_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_channel_connections( + eventarc.ListChannelConnectionsRequest(), + parent="parent_value", + ) + + +def test_list_channel_connections_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + next_page_token="abc", + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[], + next_page_token="def", + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + ], + next_page_token="ghi", + ), + eventarc.ListChannelConnectionsResponse( + channel_connections=[ + channel_connection.ChannelConnection(), + channel_connection.ChannelConnection(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + eventarc.ListChannelConnectionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_channel_connections(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, channel_connection.ChannelConnection) for i in results) + + pages = list(client.list_channel_connections(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_channel_connection_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 = EventarcClient( + 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.create_channel_connection + 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.create_channel_connection + ] = mock_rpc + + request = {} + client.create_channel_connection(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.create_channel_connection(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_create_channel_connection_rest_required_fields( + request_type=eventarc.CreateChannelConnectionRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["channel_connection_id"] = "" + 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 + assert "channelConnectionId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_channel_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "channelConnectionId" in jsonified_request + assert ( + jsonified_request["channelConnectionId"] + == request_init["channel_connection_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["channelConnectionId"] = "channel_connection_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_channel_connection._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("channel_connection_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "channelConnectionId" in jsonified_request + assert jsonified_request["channelConnectionId"] == "channel_connection_id_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_channel_connection(request) + + expected_params = [ + ( + "channelConnectionId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_channel_connection_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_channel_connection._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("channelConnectionId",)) + & set( + ( + "parent", + "channelConnection", + "channelConnectionId", + ) + ) + ) + + +def test_create_channel_connection_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + channel_connection=gce_channel_connection.ChannelConnection( + name="name_value" + ), + channel_connection_id="channel_connection_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_channel_connection(**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/v1/{parent=projects/*/locations/*}/channelConnections" + % client.transport._host, + args[1], + ) + + +def test_create_channel_connection_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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.create_channel_connection( + eventarc.CreateChannelConnectionRequest(), + parent="parent_value", + channel_connection=gce_channel_connection.ChannelConnection( + name="name_value" + ), + channel_connection_id="channel_connection_id_value", + ) + + +def test_delete_channel_connection_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 = EventarcClient( + 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_channel_connection + 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_channel_connection + ] = mock_rpc + + request = {} + client.delete_channel_connection(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_channel_connection(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_channel_connection_rest_required_fields( + request_type=eventarc.DeleteChannelConnectionRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_channel_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_channel_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_channel_connection(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_channel_connection_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_channel_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_channel_connection_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/channelConnections/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_channel_connection(**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/v1/{name=projects/*/locations/*/channelConnections/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_channel_connection_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_channel_connection( + eventarc.DeleteChannelConnectionRequest(), + name="name_value", + ) + + +def test_get_google_channel_config_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 = EventarcClient( + 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_google_channel_config + 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_google_channel_config + ] = mock_rpc + + request = {} + client.get_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_channel_config(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_google_channel_config_rest_required_fields( + request_type=eventarc.GetGoogleChannelConfigRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_google_channel_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_google_channel_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = google_channel_config.GoogleChannelConfig() + # 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 = google_channel_config.GoogleChannelConfig.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 + + response = client.get_google_channel_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_google_channel_config_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_google_channel_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_google_channel_config_rest_flattened(): + client = EventarcClient( + 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 = google_channel_config.GoogleChannelConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/googleChannelConfig" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = google_channel_config.GoogleChannelConfig.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 + + client.get_google_channel_config(**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/v1/{name=projects/*/locations/*/googleChannelConfig}" + % client.transport._host, + args[1], + ) + + +def test_get_google_channel_config_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_google_channel_config( + eventarc.GetGoogleChannelConfigRequest(), + name="name_value", + ) + + +def test_update_google_channel_config_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 = EventarcClient( + 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_google_channel_config + 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_google_channel_config + ] = mock_rpc + + request = {} + client.update_google_channel_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_channel_config(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_google_channel_config_rest_required_fields( + request_type=eventarc.UpdateGoogleChannelConfigRequest, +): + transport_class = transports.EventarcRestTransport + + 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() + ).update_google_channel_config._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() + ).update_google_channel_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gce_google_channel_config.GoogleChannelConfig() + # 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 = gce_google_channel_config.GoogleChannelConfig.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 + + response = client.update_google_channel_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_google_channel_config_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_google_channel_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("googleChannelConfig",))) + + +def test_update_google_channel_config_rest_flattened(): + client = EventarcClient( + 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 = gce_google_channel_config.GoogleChannelConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "google_channel_config": { + "name": "projects/sample1/locations/sample2/googleChannelConfig" + } + } + + # get truthy value for each flattened field + mock_args = dict( + google_channel_config=gce_google_channel_config.GoogleChannelConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = gce_google_channel_config.GoogleChannelConfig.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 + + client.update_google_channel_config(**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/v1/{google_channel_config.name=projects/*/locations/*/googleChannelConfig}" + % client.transport._host, + args[1], + ) + + +def test_update_google_channel_config_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_google_channel_config( + eventarc.UpdateGoogleChannelConfigRequest(), + google_channel_config=gce_google_channel_config.GoogleChannelConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus] = mock_rpc + + request = {} + client.get_message_bus(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_message_bus(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_message_bus_rest_required_fields( + request_type=eventarc.GetMessageBusRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_message_bus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_message_bus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = message_bus.MessageBus() + # 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 = message_bus.MessageBus.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 + + response = client.get_message_bus(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_message_bus_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_message_bus._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_message_bus_rest_flattened(): + client = EventarcClient( + 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 = message_bus.MessageBus() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/messageBuses/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = message_bus.MessageBus.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 + + client.get_message_bus(**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/v1/{name=projects/*/locations/*/messageBuses/*}" + % client.transport._host, + args[1], + ) + + +def test_get_message_bus_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_message_bus( + eventarc.GetMessageBusRequest(), + name="name_value", + ) + + +def test_list_message_buses_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 = EventarcClient( + 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_message_buses 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_message_buses + ] = mock_rpc + + request = {} + client.list_message_buses(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_message_buses(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_message_buses_rest_required_fields( + request_type=eventarc.ListMessageBusesRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_message_buses._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_message_buses._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListMessageBusesResponse() + # 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 = eventarc.ListMessageBusesResponse.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 + + response = client.list_message_buses(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_message_buses_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_message_buses._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_message_buses_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListMessageBusesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListMessageBusesResponse.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 + + client.list_message_buses(**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/v1/{parent=projects/*/locations/*}/messageBuses" + % client.transport._host, + args[1], + ) + + +def test_list_message_buses_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_message_buses( + eventarc.ListMessageBusesRequest(), + parent="parent_value", + ) + + +def test_list_message_buses_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusesResponse( + message_buses=[], + next_page_token="def", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusesResponse( + message_buses=[ + message_bus.MessageBus(), + message_bus.MessageBus(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListMessageBusesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_message_buses(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message_bus.MessageBus) for i in results) + + pages = list(client.list_message_buses(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_message_bus_enrollments_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 = EventarcClient( + 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_message_bus_enrollments + 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_message_bus_enrollments + ] = mock_rpc + + request = {} + client.list_message_bus_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_message_bus_enrollments(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_message_bus_enrollments_rest_required_fields( + request_type=eventarc.ListMessageBusEnrollmentsRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_message_bus_enrollments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_message_bus_enrollments._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListMessageBusEnrollmentsResponse() + # 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 = eventarc.ListMessageBusEnrollmentsResponse.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 + + response = client.list_message_bus_enrollments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_message_bus_enrollments_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_message_bus_enrollments._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_message_bus_enrollments_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListMessageBusEnrollmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/messageBuses/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListMessageBusEnrollmentsResponse.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 + + client.list_message_bus_enrollments(**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/v1/{parent=projects/*/locations/*/messageBuses/*}:listEnrollments" + % client.transport._host, + args[1], + ) + + +def test_list_message_bus_enrollments_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_message_bus_enrollments( + eventarc.ListMessageBusEnrollmentsRequest(), + parent="parent_value", + ) + + +def test_list_message_bus_enrollments_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + str(), + ], + next_page_token="abc", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + ], + next_page_token="ghi", + ), + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=[ + str(), + str(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + eventarc.ListMessageBusEnrollmentsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/messageBuses/sample3" + } + + pager = client.list_message_bus_enrollments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, str) for i in results) + + pages = list(client.list_message_bus_enrollments(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_message_bus_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 = EventarcClient( + 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.create_message_bus 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.create_message_bus + ] = mock_rpc + + request = {} + client.create_message_bus(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.create_message_bus(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_create_message_bus_rest_required_fields( + request_type=eventarc.CreateMessageBusRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["message_bus_id"] = "" + 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 + assert "messageBusId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_message_bus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "messageBusId" in jsonified_request + assert jsonified_request["messageBusId"] == request_init["message_bus_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["messageBusId"] = "message_bus_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_message_bus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "message_bus_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "messageBusId" in jsonified_request + assert jsonified_request["messageBusId"] == "message_bus_id_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_message_bus(request) + + expected_params = [ + ( + "messageBusId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_message_bus_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_message_bus._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "messageBusId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "messageBus", + "messageBusId", + ) + ) + ) + + +def test_create_message_bus_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + message_bus=gce_message_bus.MessageBus(name="name_value"), + message_bus_id="message_bus_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_message_bus(**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/v1/{parent=projects/*/locations/*}/messageBuses" + % client.transport._host, + args[1], + ) + + +def test_create_message_bus_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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.create_message_bus( + eventarc.CreateMessageBusRequest(), + parent="parent_value", + message_bus=gce_message_bus.MessageBus(name="name_value"), + message_bus_id="message_bus_id_value", + ) + + +def test_update_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus + ] = mock_rpc + + request = {} + client.update_message_bus(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_message_bus(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_message_bus_rest_required_fields( + request_type=eventarc.UpdateMessageBusRequest, +): + transport_class = transports.EventarcRestTransport + + 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() + ).update_message_bus._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() + ).update_message_bus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "update_mask", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_message_bus(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_message_bus_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_message_bus._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "updateMask", + "validateOnly", + ) + ) + & set(("messageBus",)) + ) + + +def test_update_message_bus_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "message_bus": { + "name": "projects/sample1/locations/sample2/messageBuses/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + message_bus=gce_message_bus.MessageBus(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_message_bus(**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/v1/{message_bus.name=projects/*/locations/*/messageBuses/*}" + % client.transport._host, + args[1], + ) + + +def test_update_message_bus_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_message_bus( + eventarc.UpdateMessageBusRequest(), + message_bus=gce_message_bus.MessageBus(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_message_bus_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 = EventarcClient( + 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_message_bus 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_message_bus + ] = mock_rpc + + request = {} + client.delete_message_bus(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_message_bus(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_message_bus_rest_required_fields( + request_type=eventarc.DeleteMessageBusRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_message_bus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_message_bus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "etag", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_message_bus(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_message_bus_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_message_bus._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +def test_delete_message_bus_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/messageBuses/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + etag="etag_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_message_bus(**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/v1/{name=projects/*/locations/*/messageBuses/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_message_bus_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_message_bus( + eventarc.DeleteMessageBusRequest(), + name="name_value", + etag="etag_value", + ) + + +def test_get_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment] = mock_rpc + + request = {} + client.get_enrollment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_enrollment(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_enrollment_rest_required_fields( + request_type=eventarc.GetEnrollmentRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_enrollment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_enrollment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = enrollment.Enrollment() + # 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 = enrollment.Enrollment.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 + + response = client.get_enrollment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_enrollment_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_enrollment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_enrollment_rest_flattened(): + client = EventarcClient( + 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 = enrollment.Enrollment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/enrollments/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = enrollment.Enrollment.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 + + client.get_enrollment(**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/v1/{name=projects/*/locations/*/enrollments/*}" + % client.transport._host, + args[1], + ) + + +def test_get_enrollment_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_enrollment( + eventarc.GetEnrollmentRequest(), + name="name_value", + ) + + +def test_list_enrollments_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 = EventarcClient( + 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_enrollments 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_enrollments + ] = mock_rpc + + request = {} + client.list_enrollments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_enrollments(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_enrollments_rest_required_fields( + request_type=eventarc.ListEnrollmentsRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_enrollments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_enrollments._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListEnrollmentsResponse() + # 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 = eventarc.ListEnrollmentsResponse.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 + + response = client.list_enrollments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_enrollments_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_enrollments._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_enrollments_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListEnrollmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListEnrollmentsResponse.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 + + client.list_enrollments(**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/v1/{parent=projects/*/locations/*}/enrollments" + % client.transport._host, + args[1], + ) + + +def test_list_enrollments_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_enrollments( + eventarc.ListEnrollmentsRequest(), + parent="parent_value", + ) + + +def test_list_enrollments_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + next_page_token="abc", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[], + next_page_token="def", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + ], + next_page_token="ghi", + ), + eventarc.ListEnrollmentsResponse( + enrollments=[ + enrollment.Enrollment(), + enrollment.Enrollment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListEnrollmentsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_enrollments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, enrollment.Enrollment) for i in results) + + pages = list(client.list_enrollments(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_enrollment_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 = EventarcClient( + 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.create_enrollment 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.create_enrollment + ] = mock_rpc + + request = {} + client.create_enrollment(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.create_enrollment(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_create_enrollment_rest_required_fields( + request_type=eventarc.CreateEnrollmentRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["enrollment_id"] = "" + 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 + assert "enrollmentId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_enrollment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "enrollmentId" in jsonified_request + assert jsonified_request["enrollmentId"] == request_init["enrollment_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["enrollmentId"] = "enrollment_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_enrollment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "enrollment_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "enrollmentId" in jsonified_request + assert jsonified_request["enrollmentId"] == "enrollment_id_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_enrollment(request) + + expected_params = [ + ( + "enrollmentId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_enrollment_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_enrollment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "enrollmentId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "enrollment", + "enrollmentId", + ) + ) + ) + + +def test_create_enrollment_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + enrollment=gce_enrollment.Enrollment(name="name_value"), + enrollment_id="enrollment_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_enrollment(**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/v1/{parent=projects/*/locations/*}/enrollments" + % client.transport._host, + args[1], + ) + + +def test_create_enrollment_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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.create_enrollment( + eventarc.CreateEnrollmentRequest(), + parent="parent_value", + enrollment=gce_enrollment.Enrollment(name="name_value"), + enrollment_id="enrollment_id_value", + ) + + +def test_update_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment + ] = mock_rpc + + request = {} + client.update_enrollment(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_enrollment(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_enrollment_rest_required_fields( + request_type=eventarc.UpdateEnrollmentRequest, +): + transport_class = transports.EventarcRestTransport + + 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() + ).update_enrollment._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() + ).update_enrollment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "update_mask", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_enrollment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_enrollment_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_enrollment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "updateMask", + "validateOnly", + ) + ) + & set(("enrollment",)) + ) + + +def test_update_enrollment_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "enrollment": { + "name": "projects/sample1/locations/sample2/enrollments/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + enrollment=gce_enrollment.Enrollment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_enrollment(**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/v1/{enrollment.name=projects/*/locations/*/enrollments/*}" + % client.transport._host, + args[1], + ) + + +def test_update_enrollment_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_enrollment( + eventarc.UpdateEnrollmentRequest(), + enrollment=gce_enrollment.Enrollment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_enrollment_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 = EventarcClient( + 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_enrollment 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_enrollment + ] = mock_rpc + + request = {} + client.delete_enrollment(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_enrollment(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_enrollment_rest_required_fields( + request_type=eventarc.DeleteEnrollmentRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_enrollment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_enrollment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "etag", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_enrollment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_enrollment_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_enrollment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +def test_delete_enrollment_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/enrollments/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + etag="etag_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_enrollment(**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/v1/{name=projects/*/locations/*/enrollments/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_enrollment_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_enrollment( + eventarc.DeleteEnrollmentRequest(), + name="name_value", + etag="etag_value", + ) + + +def test_get_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + client.get_pipeline(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_pipeline(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_pipeline_rest_required_fields(request_type=eventarc.GetPipelineRequest): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_pipeline._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_pipeline._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = pipeline.Pipeline() + # 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 = pipeline.Pipeline.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 + + response = client.get_pipeline(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_pipeline_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_pipeline._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_pipeline_rest_flattened(): + client = EventarcClient( + 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 = pipeline.Pipeline() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/pipelines/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = pipeline.Pipeline.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 + + client.get_pipeline(**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/v1/{name=projects/*/locations/*/pipelines/*}" % client.transport._host, + args[1], + ) + + +def test_get_pipeline_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_pipeline( + eventarc.GetPipelineRequest(), + name="name_value", + ) + + +def test_list_pipelines_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 = EventarcClient( + 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_pipelines 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_pipelines] = mock_rpc + + request = {} + client.list_pipelines(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_pipelines(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_pipelines_rest_required_fields( + request_type=eventarc.ListPipelinesRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_pipelines._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_pipelines._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListPipelinesResponse() + # 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 = eventarc.ListPipelinesResponse.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 + + response = client.list_pipelines(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_pipelines_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_pipelines._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_pipelines_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListPipelinesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListPipelinesResponse.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 + + client.list_pipelines(**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/v1/{parent=projects/*/locations/*}/pipelines" % client.transport._host, + args[1], + ) + + +def test_list_pipelines_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_pipelines( + eventarc.ListPipelinesRequest(), + parent="parent_value", + ) + + +def test_list_pipelines_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + next_page_token="abc", + ), + eventarc.ListPipelinesResponse( + pipelines=[], + next_page_token="def", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + ], + next_page_token="ghi", + ), + eventarc.ListPipelinesResponse( + pipelines=[ + pipeline.Pipeline(), + pipeline.Pipeline(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(eventarc.ListPipelinesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_pipelines(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, pipeline.Pipeline) for i in results) + + pages = list(client.list_pipelines(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_pipeline_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 = EventarcClient( + 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.create_pipeline 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.create_pipeline] = mock_rpc + + request = {} + client.create_pipeline(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.create_pipeline(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_create_pipeline_rest_required_fields( + request_type=eventarc.CreatePipelineRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["pipeline_id"] = "" + 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 + assert "pipelineId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_pipeline._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "pipelineId" in jsonified_request + assert jsonified_request["pipelineId"] == request_init["pipeline_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["pipelineId"] = "pipeline_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_pipeline._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pipeline_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "pipelineId" in jsonified_request + assert jsonified_request["pipelineId"] == "pipeline_id_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_pipeline(request) + + expected_params = [ + ( + "pipelineId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_pipeline_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_pipeline._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pipelineId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "pipeline", + "pipelineId", + ) + ) + ) + + +def test_create_pipeline_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + pipeline=gce_pipeline.Pipeline(name="name_value"), + pipeline_id="pipeline_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_pipeline(**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/v1/{parent=projects/*/locations/*}/pipelines" % client.transport._host, + args[1], + ) + + +def test_create_pipeline_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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.create_pipeline( + eventarc.CreatePipelineRequest(), + parent="parent_value", + pipeline=gce_pipeline.Pipeline(name="name_value"), + pipeline_id="pipeline_id_value", + ) + + +def test_update_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + client.update_pipeline(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_pipeline(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_pipeline_rest_required_fields( + request_type=eventarc.UpdatePipelineRequest, +): + transport_class = transports.EventarcRestTransport + + 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() + ).update_pipeline._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() + ).update_pipeline._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "update_mask", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_pipeline(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_pipeline_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_pipeline._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "updateMask", + "validateOnly", + ) + ) + & set(("pipeline",)) + ) + + +def test_update_pipeline_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "pipeline": {"name": "projects/sample1/locations/sample2/pipelines/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + pipeline=gce_pipeline.Pipeline(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_pipeline(**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/v1/{pipeline.name=projects/*/locations/*/pipelines/*}" + % client.transport._host, + args[1], + ) + + +def test_update_pipeline_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_pipeline( + eventarc.UpdatePipelineRequest(), + pipeline=gce_pipeline.Pipeline(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_pipeline_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 = EventarcClient( + 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_pipeline 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_pipeline] = mock_rpc + + request = {} + client.delete_pipeline(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_pipeline(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_pipeline_rest_required_fields( + request_type=eventarc.DeletePipelineRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_pipeline._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_pipeline._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "etag", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_pipeline(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_pipeline_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_pipeline._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +def test_delete_pipeline_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/pipelines/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + etag="etag_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_pipeline(**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/v1/{name=projects/*/locations/*/pipelines/*}" % client.transport._host, + args[1], + ) + + +def test_delete_pipeline_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_pipeline( + eventarc.DeletePipelineRequest(), + name="name_value", + etag="etag_value", + ) + + +def test_get_google_api_source_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 = EventarcClient( + 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_google_api_source + 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_google_api_source + ] = mock_rpc + + request = {} + client.get_google_api_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_api_source(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_google_api_source_rest_required_fields( + request_type=eventarc.GetGoogleApiSourceRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_google_api_source._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_google_api_source._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = google_api_source.GoogleApiSource() + # 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 = google_api_source.GoogleApiSource.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 + + response = client.get_google_api_source(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_google_api_source_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_google_api_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_google_api_source_rest_flattened(): + client = EventarcClient( + 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 = google_api_source.GoogleApiSource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/googleApiSources/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = google_api_source.GoogleApiSource.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 + + client.get_google_api_source(**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/v1/{name=projects/*/locations/*/googleApiSources/*}" + % client.transport._host, + args[1], + ) + + +def test_get_google_api_source_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_google_api_source( + eventarc.GetGoogleApiSourceRequest(), + name="name_value", + ) + + +def test_list_google_api_sources_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 = EventarcClient( + 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_google_api_sources + 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_google_api_sources + ] = mock_rpc + + request = {} + client.list_google_api_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_google_api_sources(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_google_api_sources_rest_required_fields( + request_type=eventarc.ListGoogleApiSourcesRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_google_api_sources._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_google_api_sources._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = eventarc.ListGoogleApiSourcesResponse() + # 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 = eventarc.ListGoogleApiSourcesResponse.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 + + response = client.list_google_api_sources(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_google_api_sources_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_google_api_sources._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_google_api_sources_rest_flattened(): + client = EventarcClient( + 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 = eventarc.ListGoogleApiSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_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 = eventarc.ListGoogleApiSourcesResponse.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 + + client.list_google_api_sources(**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/v1/{parent=projects/*/locations/*}/googleApiSources" + % client.transport._host, + args[1], + ) + + +def test_list_google_api_sources_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_google_api_sources( + eventarc.ListGoogleApiSourcesRequest(), + parent="parent_value", + ) + + +def test_list_google_api_sources_rest_pager(transport: str = "rest"): + client = EventarcClient( + 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 = ( + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + next_page_token="abc", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[], + next_page_token="def", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + ], + next_page_token="ghi", + ), + eventarc.ListGoogleApiSourcesResponse( + google_api_sources=[ + google_api_source.GoogleApiSource(), + google_api_source.GoogleApiSource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + eventarc.ListGoogleApiSourcesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_google_api_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, google_api_source.GoogleApiSource) for i in results) + + pages = list(client.list_google_api_sources(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_google_api_source_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 = EventarcClient( + 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.create_google_api_source + 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.create_google_api_source + ] = mock_rpc + + request = {} + client.create_google_api_source(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.create_google_api_source(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_create_google_api_source_rest_required_fields( + request_type=eventarc.CreateGoogleApiSourceRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["google_api_source_id"] = "" + 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 + assert "googleApiSourceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_google_api_source._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "googleApiSourceId" in jsonified_request + assert ( + jsonified_request["googleApiSourceId"] == request_init["google_api_source_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["googleApiSourceId"] = "google_api_source_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_google_api_source._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "google_api_source_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "googleApiSourceId" in jsonified_request + assert jsonified_request["googleApiSourceId"] == "google_api_source_id_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_google_api_source(request) + + expected_params = [ + ( + "googleApiSourceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_google_api_source_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_google_api_source._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "googleApiSourceId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "googleApiSource", + "googleApiSourceId", + ) + ) + ) + + +def test_create_google_api_source_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + google_api_source_id="google_api_source_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_google_api_source(**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/v1/{parent=projects/*/locations/*}/googleApiSources" + % client.transport._host, + args[1], + ) + + +def test_create_google_api_source_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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.create_google_api_source( + eventarc.CreateGoogleApiSourceRequest(), + parent="parent_value", + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + google_api_source_id="google_api_source_id_value", + ) + + +def test_update_google_api_source_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 = EventarcClient( + 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_google_api_source + 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_google_api_source + ] = mock_rpc + + request = {} + client.update_google_api_source(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_google_api_source(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_google_api_source_rest_required_fields( + request_type=eventarc.UpdateGoogleApiSourceRequest, +): + transport_class = transports.EventarcRestTransport + + 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() + ).update_google_api_source._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() + ).update_google_api_source._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "update_mask", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_google_api_source(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_google_api_source_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_google_api_source._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "updateMask", + "validateOnly", + ) + ) + & set(("googleApiSource",)) + ) + + +def test_update_google_api_source_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "google_api_source": { + "name": "projects/sample1/locations/sample2/googleApiSources/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_google_api_source(**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/v1/{google_api_source.name=projects/*/locations/*/googleApiSources/*}" + % client.transport._host, + args[1], + ) + + +def test_update_google_api_source_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_google_api_source( + eventarc.UpdateGoogleApiSourceRequest(), + google_api_source=gce_google_api_source.GoogleApiSource(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_google_api_source_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 = EventarcClient( + 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_google_api_source + 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_google_api_source + ] = mock_rpc + + request = {} + client.delete_google_api_source(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_google_api_source(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_google_api_source_rest_required_fields( + request_type=eventarc.DeleteGoogleApiSourceRequest, +): + transport_class = transports.EventarcRestTransport + + request_init = {} + request_init["name"] = "" + 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_google_api_source._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_google_api_source._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "etag", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_google_api_source(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_google_api_source_rest_unset_required_fields(): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_google_api_source._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +def test_delete_google_api_source_rest_flattened(): + client = EventarcClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/googleApiSources/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + etag="etag_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_google_api_source(**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/v1/{name=projects/*/locations/*/googleApiSources/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_google_api_source_rest_flattened_error(transport: str = "rest"): + client = EventarcClient( + 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_google_api_source( + eventarc.DeleteGoogleApiSourceRequest(), + name="name_value", + etag="etag_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EventarcClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EventarcClient( + 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 = EventarcClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EventarcClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EventarcClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EventarcGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EventarcGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EventarcGrpcTransport, + transports.EventarcGrpcAsyncIOTransport, + transports.EventarcRestTransport, + ], +) +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_grpc(): + transport = EventarcClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + 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_trigger_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_trigger), "__call__") as call: + call.return_value = trigger.Trigger() + client.get_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetTriggerRequest() + + 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_triggers_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_triggers), "__call__") as call: + call.return_value = eventarc.ListTriggersResponse() + client.list_triggers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListTriggersRequest() + + 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_create_trigger_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_trigger), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateTriggerRequest() + + 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_trigger_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_trigger), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateTriggerRequest() + + 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_trigger_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_trigger), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteTriggerRequest() + + 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_channel_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_channel), "__call__") as call: + call.return_value = channel.Channel() + client.get_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelRequest() + + 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_channels_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_channels), "__call__") as call: + call.return_value = eventarc.ListChannelsResponse() + client.list_channels(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelsRequest() + + 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_create_channel_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelRequest() + + 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_channel_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_channel), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateChannelRequest() + + 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_channel_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelRequest() + + 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_provider_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_provider), "__call__") as call: + call.return_value = discovery.Provider() + client.get_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetProviderRequest() + + 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_providers_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_providers), "__call__") as call: + call.return_value = eventarc.ListProvidersResponse() + client.list_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListProvidersRequest() + + 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_channel_connection_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), "__call__" + ) as call: + call.return_value = channel_connection.ChannelConnection() + client.get_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelConnectionRequest() + + 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_channel_connections_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), "__call__" + ) as call: + call.return_value = eventarc.ListChannelConnectionsResponse() + client.list_channel_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelConnectionsRequest() + + 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_create_channel_connection_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelConnectionRequest() + + 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_channel_connection_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelConnectionRequest() + + 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_google_channel_config_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), "__call__" + ) as call: + call.return_value = google_channel_config.GoogleChannelConfig() + client.get_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleChannelConfigRequest() + + 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_google_channel_config_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), "__call__" + ) as call: + call.return_value = gce_google_channel_config.GoogleChannelConfig() + client.update_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleChannelConfigRequest() + + 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_message_bus_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + call.return_value = message_bus.MessageBus() + client.get_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetMessageBusRequest() + + 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_message_buses_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + call.return_value = eventarc.ListMessageBusesResponse() + client.list_message_buses(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusesRequest() + + 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_message_bus_enrollments_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + call.return_value = eventarc.ListMessageBusEnrollmentsResponse() + client.list_message_bus_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusEnrollmentsRequest() + + 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_create_message_bus_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateMessageBusRequest() + + 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_message_bus_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateMessageBusRequest() + + 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_message_bus_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteMessageBusRequest() + + 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_enrollment_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + call.return_value = enrollment.Enrollment() + client.get_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetEnrollmentRequest() + + 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_enrollments_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + call.return_value = eventarc.ListEnrollmentsResponse() + client.list_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListEnrollmentsRequest() + + 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_create_enrollment_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateEnrollmentRequest() + + 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_enrollment_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateEnrollmentRequest() + + 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_enrollment_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteEnrollmentRequest() + + 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_pipeline_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + call.return_value = pipeline.Pipeline() + client.get_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetPipelineRequest() + + 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_pipelines_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + call.return_value = eventarc.ListPipelinesResponse() + client.list_pipelines(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListPipelinesRequest() + + 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_create_pipeline_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreatePipelineRequest() + + 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_pipeline_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdatePipelineRequest() + + 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_pipeline_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeletePipelineRequest() + + 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_google_api_source_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + call.return_value = google_api_source.GoogleApiSource() + client.get_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleApiSourceRequest() + + 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_google_api_sources_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + call.return_value = eventarc.ListGoogleApiSourcesResponse() + client.list_google_api_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListGoogleApiSourcesRequest() + + 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_create_google_api_source_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateGoogleApiSourceRequest() + + 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_google_api_source_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleApiSourceRequest() + + 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_google_api_source_empty_call_grpc(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteGoogleApiSourceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = EventarcAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + 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. +@pytest.mark.asyncio +async def test_get_trigger_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_trigger), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + trigger.Trigger( + name="name_value", + uid="uid_value", + service_account="service_account_value", + channel="channel_value", + event_data_content_type="event_data_content_type_value", + satisfies_pzs=True, + etag="etag_value", + ) + ) + await client.get_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetTriggerRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_triggers_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_triggers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListTriggersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_triggers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListTriggersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_trigger_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_trigger), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateTriggerRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_trigger_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_trigger), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateTriggerRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_trigger_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_trigger), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteTriggerRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_channel_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_channel), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + channel.Channel( + name="name_value", + uid="uid_value", + provider="provider_value", + state=channel.Channel.State.PENDING, + activation_token="activation_token_value", + crypto_key_name="crypto_key_name_value", + satisfies_pzs=True, + ) + ) + await client.get_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_channels_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_channels), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListChannelsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_channels(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_channel_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_channel_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_channel), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_channel_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_provider_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_provider), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + discovery.Provider( + name="name_value", + display_name="display_name_value", + ) + ) + await client.get_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetProviderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_providers_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_providers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListProvidersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListProvidersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_channel_connection_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + channel_connection.ChannelConnection( + name="name_value", + uid="uid_value", + channel="channel_value", + activation_token="activation_token_value", + ) + ) + await client.get_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_channel_connections_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListChannelConnectionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_channel_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelConnectionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_channel_connection_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_channel_connection_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_google_channel_config_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + google_channel_config.GoogleChannelConfig( + name="name_value", + crypto_key_name="crypto_key_name_value", + ) + ) + await client.get_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleChannelConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_google_channel_config_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gce_google_channel_config.GoogleChannelConfig( + name="name_value", + crypto_key_name="crypto_key_name_value", + ) + ) + await client.update_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleChannelConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_message_bus_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message_bus.MessageBus( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + crypto_key_name="crypto_key_name_value", + ) + ) + await client.get_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetMessageBusRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_message_buses_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListMessageBusesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_message_buses(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_message_bus_enrollments_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListMessageBusEnrollmentsResponse( + enrollments=["enrollments_value"], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_message_bus_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusEnrollmentsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_message_bus_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateMessageBusRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_message_bus_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateMessageBusRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_message_bus_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_message_bus(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteMessageBusRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_enrollment_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + enrollment.Enrollment( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + cel_match="cel_match_value", + message_bus="message_bus_value", + destination="destination_value", + ) + ) + await client.get_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetEnrollmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_enrollments_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListEnrollmentsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListEnrollmentsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_enrollment_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateEnrollmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_enrollment_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateEnrollmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_enrollment_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_enrollment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteEnrollmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_pipeline_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + pipeline.Pipeline( + name="name_value", + uid="uid_value", + display_name="display_name_value", + crypto_key_name="crypto_key_name_value", + etag="etag_value", + ) + ) + await client.get_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetPipelineRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_pipelines_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListPipelinesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_pipelines(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListPipelinesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_pipeline_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreatePipelineRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_pipeline_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdatePipelineRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_pipeline_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_pipeline(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeletePipelineRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_google_api_source_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + google_api_source.GoogleApiSource( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + destination="destination_value", + crypto_key_name="crypto_key_name_value", + ) + ) + await client.get_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleApiSourceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_google_api_sources_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_google_api_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + eventarc.ListGoogleApiSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_google_api_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListGoogleApiSourcesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_google_api_source_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateGoogleApiSourceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_google_api_source_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleApiSourceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_google_api_source_empty_call_grpc_asyncio(): + client = EventarcAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_api_source), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_google_api_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteGoogleApiSourceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = EventarcClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_trigger_rest_bad_request(request_type=eventarc.GetTriggerRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/triggers/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 + client.get_trigger(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetTriggerRequest, + dict, + ], +) +def test_get_trigger_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/triggers/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 = trigger.Trigger( + name="name_value", + uid="uid_value", + service_account="service_account_value", + channel="channel_value", + event_data_content_type="event_data_content_type_value", + satisfies_pzs=True, + etag="etag_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 = trigger.Trigger.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 + response = client.get_trigger(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, trigger.Trigger) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.service_account == "service_account_value" + assert response.channel == "channel_value" + assert response.event_data_content_type == "event_data_content_type_value" + assert response.satisfies_pzs is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_trigger_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_trigger" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_get_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetTriggerRequest.pb(eventarc.GetTriggerRequest()) + 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 + return_value = trigger.Trigger.to_json(trigger.Trigger()) + req.return_value.content = return_value + + request = eventarc.GetTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = trigger.Trigger() + + client.get_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_triggers_rest_bad_request(request_type=eventarc.ListTriggersRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.list_triggers(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListTriggersRequest, + dict, + ], +) +def test_list_triggers_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 = eventarc.ListTriggersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = eventarc.ListTriggersResponse.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 + response = client.list_triggers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTriggersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_triggers_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_triggers" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_list_triggers" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListTriggersRequest.pb(eventarc.ListTriggersRequest()) + 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 + return_value = eventarc.ListTriggersResponse.to_json( + eventarc.ListTriggersResponse() + ) + req.return_value.content = return_value + + request = eventarc.ListTriggersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListTriggersResponse() + + client.list_triggers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_trigger_rest_bad_request(request_type=eventarc.CreateTriggerRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.create_trigger(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.CreateTriggerRequest, + dict, + ], +) +def test_create_trigger_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["trigger"] = { + "name": "name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "event_filters": [ + { + "attribute": "attribute_value", + "value": "value_value", + "operator": "operator_value", + } + ], + "service_account": "service_account_value", + "destination": { + "cloud_run": { + "service": "service_value", + "path": "path_value", + "region": "region_value", + }, + "cloud_function": "cloud_function_value", + "gke": { + "cluster": "cluster_value", + "location": "location_value", + "namespace": "namespace_value", + "service": "service_value", + "path": "path_value", + }, + "workflow": "workflow_value", + "http_endpoint": {"uri": "uri_value"}, + "network_config": {"network_attachment": "network_attachment_value"}, + }, + "transport": { + "pubsub": {"topic": "topic_value", "subscription": "subscription_value"} + }, + "labels": {}, + "channel": "channel_value", + "conditions": {}, + "event_data_content_type": "event_data_content_type_value", + "satisfies_pzs": True, + "etag": "etag_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 = eventarc.CreateTriggerRequest.meta.fields["trigger"] + + 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["trigger"].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["trigger"][field])): + del request_init["trigger"][field][i][subfield] + else: + del request_init["trigger"][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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_trigger(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_trigger_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_create_trigger" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_create_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateTriggerRequest.pb(eventarc.CreateTriggerRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_trigger_rest_bad_request(request_type=eventarc.UpdateTriggerRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "trigger": {"name": "projects/sample1/locations/sample2/triggers/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 + client.update_trigger(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.UpdateTriggerRequest, + dict, + ], +) +def test_update_trigger_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "trigger": {"name": "projects/sample1/locations/sample2/triggers/sample3"} + } + request_init["trigger"] = { + "name": "projects/sample1/locations/sample2/triggers/sample3", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "event_filters": [ + { + "attribute": "attribute_value", + "value": "value_value", + "operator": "operator_value", + } + ], + "service_account": "service_account_value", + "destination": { + "cloud_run": { + "service": "service_value", + "path": "path_value", + "region": "region_value", + }, + "cloud_function": "cloud_function_value", + "gke": { + "cluster": "cluster_value", + "location": "location_value", + "namespace": "namespace_value", + "service": "service_value", + "path": "path_value", + }, + "workflow": "workflow_value", + "http_endpoint": {"uri": "uri_value"}, + "network_config": {"network_attachment": "network_attachment_value"}, + }, + "transport": { + "pubsub": {"topic": "topic_value", "subscription": "subscription_value"} + }, + "labels": {}, + "channel": "channel_value", + "conditions": {}, + "event_data_content_type": "event_data_content_type_value", + "satisfies_pzs": True, + "etag": "etag_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 = eventarc.UpdateTriggerRequest.meta.fields["trigger"] + + 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["trigger"].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["trigger"][field])): + del request_init["trigger"][field][i][subfield] + else: + del request_init["trigger"][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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_trigger(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_trigger_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_update_trigger" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_update_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateTriggerRequest.pb(eventarc.UpdateTriggerRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdateTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_trigger_rest_bad_request(request_type=eventarc.DeleteTriggerRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/triggers/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 + client.delete_trigger(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.DeleteTriggerRequest, + dict, + ], +) +def test_delete_trigger_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/triggers/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_trigger(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_trigger_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_delete_trigger" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_delete_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteTriggerRequest.pb(eventarc.DeleteTriggerRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_channel_rest_bad_request(request_type=eventarc.GetChannelRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/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 + client.get_channel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetChannelRequest, + dict, + ], +) +def test_get_channel_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/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 = channel.Channel( + name="name_value", + uid="uid_value", + provider="provider_value", + state=channel.Channel.State.PENDING, + activation_token="activation_token_value", + crypto_key_name="crypto_key_name_value", + satisfies_pzs=True, + pubsub_topic="pubsub_topic_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 = channel.Channel.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 + response = client.get_channel(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, channel.Channel) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.provider == "provider_value" + assert response.state == channel.Channel.State.PENDING + assert response.activation_token == "activation_token_value" + assert response.crypto_key_name == "crypto_key_name_value" + assert response.satisfies_pzs is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_channel_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_channel" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_get_channel" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetChannelRequest.pb(eventarc.GetChannelRequest()) + 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 + return_value = channel.Channel.to_json(channel.Channel()) + req.return_value.content = return_value + + request = eventarc.GetChannelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = channel.Channel() + + client.get_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_channels_rest_bad_request(request_type=eventarc.ListChannelsRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.list_channels(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListChannelsRequest, + dict, + ], +) +def test_list_channels_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 = eventarc.ListChannelsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = eventarc.ListChannelsResponse.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 + response = client.list_channels(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_channels_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_channels" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_list_channels" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListChannelsRequest.pb(eventarc.ListChannelsRequest()) + 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 + return_value = eventarc.ListChannelsResponse.to_json( + eventarc.ListChannelsResponse() + ) + req.return_value.content = return_value + + request = eventarc.ListChannelsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListChannelsResponse() + + client.list_channels( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_channel_rest_bad_request(request_type=eventarc.CreateChannelRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.create_channel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.CreateChannelRequest, + dict, + ], +) +def test_create_channel_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["channel"] = { + "name": "name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "provider": "provider_value", + "pubsub_topic": "pubsub_topic_value", + "state": 1, + "activation_token": "activation_token_value", + "crypto_key_name": "crypto_key_name_value", + "satisfies_pzs": True, + } + # 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 = eventarc.CreateChannelRequest.meta.fields["channel"] + + 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["channel"].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["channel"][field])): + del request_init["channel"][field][i][subfield] + else: + del request_init["channel"][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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_channel(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_channel_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_create_channel" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_create_channel" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateChannelRequest.pb(eventarc.CreateChannelRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateChannelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_channel_rest_bad_request(request_type=eventarc.UpdateChannelRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "channel": {"name": "projects/sample1/locations/sample2/channels/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 + client.update_channel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.UpdateChannelRequest, + dict, + ], +) +def test_update_channel_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} + } + request_init["channel"] = { + "name": "projects/sample1/locations/sample2/channels/sample3", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "provider": "provider_value", + "pubsub_topic": "pubsub_topic_value", + "state": 1, + "activation_token": "activation_token_value", + "crypto_key_name": "crypto_key_name_value", + "satisfies_pzs": True, + } + # 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 = eventarc.UpdateChannelRequest.meta.fields["channel"] + + 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["channel"].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["channel"][field])): + del request_init["channel"][field][i][subfield] + else: + del request_init["channel"][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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_channel(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_channel_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_update_channel" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_update_channel" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateChannelRequest.pb(eventarc.UpdateChannelRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdateChannelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_channel_rest_bad_request(request_type=eventarc.DeleteChannelRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/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 + client.delete_channel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.DeleteChannelRequest, + dict, + ], +) +def test_delete_channel_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/channels/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_channel(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_channel_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_delete_channel" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_delete_channel" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteChannelRequest.pb(eventarc.DeleteChannelRequest()) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteChannelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_channel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_provider_rest_bad_request(request_type=eventarc.GetProviderRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/providers/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 + client.get_provider(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetProviderRequest, + dict, + ], +) +def test_get_provider_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/providers/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 = discovery.Provider( + name="name_value", + display_name="display_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 = discovery.Provider.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 + response = client.get_provider(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, discovery.Provider) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_provider_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_provider" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_get_provider" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetProviderRequest.pb(eventarc.GetProviderRequest()) + 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 + return_value = discovery.Provider.to_json(discovery.Provider()) + req.return_value.content = return_value + + request = eventarc.GetProviderRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = discovery.Provider() + + client.get_provider( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_providers_rest_bad_request(request_type=eventarc.ListProvidersRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.list_providers(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListProvidersRequest, + dict, + ], +) +def test_list_providers_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 = eventarc.ListProvidersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = eventarc.ListProvidersResponse.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 + response = client.list_providers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProvidersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_providers_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_providers" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_list_providers" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListProvidersRequest.pb(eventarc.ListProvidersRequest()) + 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 + return_value = eventarc.ListProvidersResponse.to_json( + eventarc.ListProvidersResponse() + ) + req.return_value.content = return_value + + request = eventarc.ListProvidersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListProvidersResponse() + + client.list_providers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_channel_connection_rest_bad_request( + request_type=eventarc.GetChannelConnectionRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/channelConnections/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 + client.get_channel_connection(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetChannelConnectionRequest, + dict, + ], +) +def test_get_channel_connection_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/channelConnections/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 = channel_connection.ChannelConnection( + name="name_value", + uid="uid_value", + channel="channel_value", + activation_token="activation_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 = channel_connection.ChannelConnection.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 + response = client.get_channel_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, channel_connection.ChannelConnection) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.channel == "channel_value" + assert response.activation_token == "activation_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_channel_connection_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_channel_connection" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_get_channel_connection" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetChannelConnectionRequest.pb( + eventarc.GetChannelConnectionRequest() + ) + 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 + return_value = channel_connection.ChannelConnection.to_json( + channel_connection.ChannelConnection() + ) + req.return_value.content = return_value + + request = eventarc.GetChannelConnectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = channel_connection.ChannelConnection() + + client.get_channel_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_channel_connections_rest_bad_request( + request_type=eventarc.ListChannelConnectionsRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.list_channel_connections(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListChannelConnectionsRequest, + dict, + ], +) +def test_list_channel_connections_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 = eventarc.ListChannelConnectionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = eventarc.ListChannelConnectionsResponse.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 + response = client.list_channel_connections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelConnectionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_channel_connections_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_channel_connections" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_list_channel_connections" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListChannelConnectionsRequest.pb( + eventarc.ListChannelConnectionsRequest() + ) + 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 + return_value = eventarc.ListChannelConnectionsResponse.to_json( + eventarc.ListChannelConnectionsResponse() + ) + req.return_value.content = return_value + + request = eventarc.ListChannelConnectionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListChannelConnectionsResponse() + + client.list_channel_connections( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_channel_connection_rest_bad_request( + request_type=eventarc.CreateChannelConnectionRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.create_channel_connection(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.CreateChannelConnectionRequest, + dict, + ], +) +def test_create_channel_connection_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["channel_connection"] = { + "name": "name_value", + "uid": "uid_value", + "channel": "channel_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "activation_token": "activation_token_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 = eventarc.CreateChannelConnectionRequest.meta.fields[ + "channel_connection" + ] + + 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["channel_connection"].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["channel_connection"][field])): + del request_init["channel_connection"][field][i][subfield] + else: + del request_init["channel_connection"][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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_channel_connection(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_channel_connection_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_create_channel_connection" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_create_channel_connection" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateChannelConnectionRequest.pb( + eventarc.CreateChannelConnectionRequest() + ) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateChannelConnectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_channel_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_channel_connection_rest_bad_request( + request_type=eventarc.DeleteChannelConnectionRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/channelConnections/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 + client.delete_channel_connection(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.DeleteChannelConnectionRequest, + dict, + ], +) +def test_delete_channel_connection_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/channelConnections/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_channel_connection(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_channel_connection_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_delete_channel_connection" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_delete_channel_connection" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteChannelConnectionRequest.pb( + eventarc.DeleteChannelConnectionRequest() + ) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.DeleteChannelConnectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_channel_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_google_channel_config_rest_bad_request( + request_type=eventarc.GetGoogleChannelConfigRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/googleChannelConfig"} + 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 + client.get_google_channel_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetGoogleChannelConfigRequest, + dict, + ], +) +def test_get_google_channel_config_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/googleChannelConfig"} + 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 = google_channel_config.GoogleChannelConfig( + name="name_value", + crypto_key_name="crypto_key_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 = google_channel_config.GoogleChannelConfig.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 + response = client.get_google_channel_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, google_channel_config.GoogleChannelConfig) + assert response.name == "name_value" + assert response.crypto_key_name == "crypto_key_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_google_channel_config_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_google_channel_config" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_get_google_channel_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetGoogleChannelConfigRequest.pb( + eventarc.GetGoogleChannelConfigRequest() + ) + 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 + return_value = google_channel_config.GoogleChannelConfig.to_json( + google_channel_config.GoogleChannelConfig() + ) + req.return_value.content = return_value + + request = eventarc.GetGoogleChannelConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = google_channel_config.GoogleChannelConfig() + + client.get_google_channel_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_google_channel_config_rest_bad_request( + request_type=eventarc.UpdateGoogleChannelConfigRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "google_channel_config": { + "name": "projects/sample1/locations/sample2/googleChannelConfig" + } + } + 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 + client.update_google_channel_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.UpdateGoogleChannelConfigRequest, + dict, + ], +) +def test_update_google_channel_config_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "google_channel_config": { + "name": "projects/sample1/locations/sample2/googleChannelConfig" + } + } + request_init["google_channel_config"] = { + "name": "projects/sample1/locations/sample2/googleChannelConfig", + "update_time": {"seconds": 751, "nanos": 543}, + "crypto_key_name": "crypto_key_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 = eventarc.UpdateGoogleChannelConfigRequest.meta.fields[ + "google_channel_config" + ] + + 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[ + "google_channel_config" + ].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["google_channel_config"][field])): + del request_init["google_channel_config"][field][i][subfield] + else: + del request_init["google_channel_config"][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 = gce_google_channel_config.GoogleChannelConfig( + name="name_value", + crypto_key_name="crypto_key_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 = gce_google_channel_config.GoogleChannelConfig.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 + response = client.update_google_channel_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gce_google_channel_config.GoogleChannelConfig) + assert response.name == "name_value" + assert response.crypto_key_name == "crypto_key_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_google_channel_config_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_update_google_channel_config" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_update_google_channel_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateGoogleChannelConfigRequest.pb( + eventarc.UpdateGoogleChannelConfigRequest() + ) + 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 + return_value = gce_google_channel_config.GoogleChannelConfig.to_json( + gce_google_channel_config.GoogleChannelConfig() + ) + req.return_value.content = return_value + + request = eventarc.UpdateGoogleChannelConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gce_google_channel_config.GoogleChannelConfig() + + client.update_google_channel_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_message_bus_rest_bad_request(request_type=eventarc.GetMessageBusRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/messageBuses/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 + client.get_message_bus(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.GetMessageBusRequest, + dict, + ], +) +def test_get_message_bus_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/messageBuses/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 = message_bus.MessageBus( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + crypto_key_name="crypto_key_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 = message_bus.MessageBus.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 + response = client.get_message_bus(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, message_bus.MessageBus) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.crypto_key_name == "crypto_key_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_message_bus_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_get_message_bus" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_get_message_bus" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.GetMessageBusRequest.pb(eventarc.GetMessageBusRequest()) + 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 + return_value = message_bus.MessageBus.to_json(message_bus.MessageBus()) + req.return_value.content = return_value + + request = eventarc.GetMessageBusRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = message_bus.MessageBus() + + client.get_message_bus( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_message_buses_rest_bad_request( + request_type=eventarc.ListMessageBusesRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.list_message_buses(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListMessageBusesRequest, + dict, + ], +) +def test_list_message_buses_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 = eventarc.ListMessageBusesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = eventarc.ListMessageBusesResponse.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 + response = client.list_message_buses(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_message_buses_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_message_buses" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_list_message_buses" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListMessageBusesRequest.pb( + eventarc.ListMessageBusesRequest() + ) + 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 + return_value = eventarc.ListMessageBusesResponse.to_json( + eventarc.ListMessageBusesResponse() + ) + req.return_value.content = return_value + + request = eventarc.ListMessageBusesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListMessageBusesResponse() + + client.list_message_buses( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_message_bus_enrollments_rest_bad_request( + request_type=eventarc.ListMessageBusEnrollmentsRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/messageBuses/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 + client.list_message_bus_enrollments(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.ListMessageBusEnrollmentsRequest, + dict, + ], +) +def test_list_message_bus_enrollments_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/messageBuses/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 = eventarc.ListMessageBusEnrollmentsResponse( + enrollments=["enrollments_value"], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = eventarc.ListMessageBusEnrollmentsResponse.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 + response = client.list_message_bus_enrollments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessageBusEnrollmentsPager) + assert response.enrollments == ["enrollments_value"] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_message_bus_enrollments_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(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.EventarcRestInterceptor, "post_list_message_bus_enrollments" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_list_message_bus_enrollments" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.ListMessageBusEnrollmentsRequest.pb( + eventarc.ListMessageBusEnrollmentsRequest() + ) + 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 + return_value = eventarc.ListMessageBusEnrollmentsResponse.to_json( + eventarc.ListMessageBusEnrollmentsResponse() + ) + req.return_value.content = return_value + + request = eventarc.ListMessageBusEnrollmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = eventarc.ListMessageBusEnrollmentsResponse() + + client.list_message_bus_enrollments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_message_bus_rest_bad_request( + request_type=eventarc.CreateMessageBusRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/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 + client.create_message_bus(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.CreateMessageBusRequest, + dict, + ], +) +def test_create_message_bus_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["message_bus"] = { + "name": "name_value", + "uid": "uid_value", + "etag": "etag_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "annotations": {}, + "display_name": "display_name_value", + "crypto_key_name": "crypto_key_name_value", + "logging_config": {"log_severity": 1}, + } + # 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 = eventarc.CreateMessageBusRequest.meta.fields["message_bus"] + + 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["message_bus"].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["message_bus"][field])): + del request_init["message_bus"][field][i][subfield] + else: + del request_init["message_bus"][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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_message_bus(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_message_bus_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_create_message_bus" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_create_message_bus" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.CreateMessageBusRequest.pb( + eventarc.CreateMessageBusRequest() + ) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.CreateMessageBusRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_message_bus( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_message_bus_rest_bad_request( + request_type=eventarc.UpdateMessageBusRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "message_bus": { + "name": "projects/sample1/locations/sample2/messageBuses/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 + client.update_message_bus(request) + + +@pytest.mark.parametrize( + "request_type", + [ + eventarc.UpdateMessageBusRequest, + dict, + ], +) +def test_update_message_bus_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "message_bus": { + "name": "projects/sample1/locations/sample2/messageBuses/sample3" + } + } + request_init["message_bus"] = { + "name": "projects/sample1/locations/sample2/messageBuses/sample3", + "uid": "uid_value", + "etag": "etag_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "annotations": {}, + "display_name": "display_name_value", + "crypto_key_name": "crypto_key_name_value", + "logging_config": {"log_severity": 1}, + } + # 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 = eventarc.UpdateMessageBusRequest.meta.fields["message_bus"] + + 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["message_bus"].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["message_bus"][field])): + del request_init["message_bus"][field][i][subfield] + else: + del request_init["message_bus"][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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_message_bus(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_message_bus_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + ) + client = EventarcClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_update_message_bus" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_update_message_bus" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.UpdateMessageBusRequest.pb( + eventarc.UpdateMessageBusRequest() + ) + 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 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = eventarc.UpdateMessageBusRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_message_bus( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_message_bus_rest_bad_request( + request_type=eventarc.DeleteMessageBusRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/messageBuses/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 + client.delete_message_bus(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_google_channel_config_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + eventarc.DeleteMessageBusRequest, + dict, + ], +) +def test_delete_message_bus_rest_call_success(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_google_channel_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - google_channel_config.GoogleChannelConfig( - name="name_value", - crypto_key_name="crypto_key_name_value", - ) - ) - await client.get_google_channel_config(request=None) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/messageBuses/sample3"} + request = request_type(**request_init) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleChannelConfigRequest() + # 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 = operations_pb2.Operation(name="operations/spam") - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_message_bus(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_google_channel_config_empty_call_grpc_asyncio(): - client = EventarcAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_message_bus_rest_interceptors(null_interceptor): + transport = transports.EventarcRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), ) + client = EventarcClient(transport=transport) - # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_google_channel_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gce_google_channel_config.GoogleChannelConfig( - name="name_value", - crypto_key_name="crypto_key_name_value", - ) + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_delete_message_bus" + ) as post, mock.patch.object( + transports.EventarcRestInterceptor, "pre_delete_message_bus" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = eventarc.DeleteMessageBusRequest.pb( + eventarc.DeleteMessageBusRequest() ) - await client.update_google_channel_config(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleChannelConfigRequest() + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - assert args[0] == request_msg + request = eventarc.DeleteMessageBusRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + client.delete_message_bus( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = EventarcClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() -def test_get_trigger_rest_bad_request(request_type=eventarc.GetTriggerRequest): +def test_get_enrollment_rest_bad_request(request_type=eventarc.GetEnrollmentRequest): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/triggers/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/enrollments/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12868,34 +29993,36 @@ def test_get_trigger_rest_bad_request(request_type=eventarc.GetTriggerRequest): response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_trigger(request) + client.get_enrollment(request) @pytest.mark.parametrize( "request_type", [ - eventarc.GetTriggerRequest, + eventarc.GetEnrollmentRequest, dict, ], ) -def test_get_trigger_rest_call_success(request_type): +def test_get_enrollment_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/triggers/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/enrollments/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 = trigger.Trigger( + return_value = enrollment.Enrollment( name="name_value", uid="uid_value", - service_account="service_account_value", - channel="channel_value", etag="etag_value", + display_name="display_name_value", + cel_match="cel_match_value", + message_bus="message_bus_value", + destination="destination_value", ) # Wrap the value into a proper Response obj @@ -12903,23 +30030,25 @@ def test_get_trigger_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = trigger.Trigger.pb(return_value) + return_value = enrollment.Enrollment.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 - response = client.get_trigger(request) + response = client.get_enrollment(request) # Establish that the response is the type that we expect. - assert isinstance(response, trigger.Trigger) + assert isinstance(response, enrollment.Enrollment) assert response.name == "name_value" assert response.uid == "uid_value" - assert response.service_account == "service_account_value" - assert response.channel == "channel_value" assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.cel_match == "cel_match_value" + assert response.message_bus == "message_bus_value" + assert response.destination == "destination_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_trigger_rest_interceptors(null_interceptor): +def test_get_enrollment_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -12931,13 +30060,13 @@ def test_get_trigger_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EventarcRestInterceptor, "post_get_trigger" + transports.EventarcRestInterceptor, "post_get_enrollment" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_get_trigger" + transports.EventarcRestInterceptor, "pre_get_enrollment" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.GetTriggerRequest.pb(eventarc.GetTriggerRequest()) + pb_message = eventarc.GetEnrollmentRequest.pb(eventarc.GetEnrollmentRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12947,18 +30076,18 @@ def test_get_trigger_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = trigger.Trigger.to_json(trigger.Trigger()) + return_value = enrollment.Enrollment.to_json(enrollment.Enrollment()) req.return_value.content = return_value - request = eventarc.GetTriggerRequest() + request = eventarc.GetEnrollmentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = trigger.Trigger() + post.return_value = enrollment.Enrollment() - client.get_trigger( + client.get_enrollment( request, metadata=[ ("key", "val"), @@ -12970,7 +30099,9 @@ def test_get_trigger_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_triggers_rest_bad_request(request_type=eventarc.ListTriggersRequest): +def test_list_enrollments_rest_bad_request( + request_type=eventarc.ListEnrollmentsRequest, +): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12989,17 +30120,17 @@ def test_list_triggers_rest_bad_request(request_type=eventarc.ListTriggersReques response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_triggers(request) + client.list_enrollments(request) @pytest.mark.parametrize( "request_type", [ - eventarc.ListTriggersRequest, + eventarc.ListEnrollmentsRequest, dict, ], ) -def test_list_triggers_rest_call_success(request_type): +def test_list_enrollments_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13011,7 +30142,7 @@ def test_list_triggers_rest_call_success(request_type): # 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 = eventarc.ListTriggersResponse( + return_value = eventarc.ListEnrollmentsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -13021,20 +30152,20 @@ def test_list_triggers_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = eventarc.ListTriggersResponse.pb(return_value) + return_value = eventarc.ListEnrollmentsResponse.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 - response = client.list_triggers(request) + response = client.list_enrollments(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTriggersPager) + assert isinstance(response, pagers.ListEnrollmentsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_triggers_rest_interceptors(null_interceptor): +def test_list_enrollments_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -13046,13 +30177,15 @@ def test_list_triggers_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EventarcRestInterceptor, "post_list_triggers" + transports.EventarcRestInterceptor, "post_list_enrollments" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_list_triggers" + transports.EventarcRestInterceptor, "pre_list_enrollments" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.ListTriggersRequest.pb(eventarc.ListTriggersRequest()) + pb_message = eventarc.ListEnrollmentsRequest.pb( + eventarc.ListEnrollmentsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13062,20 +30195,20 @@ def test_list_triggers_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = eventarc.ListTriggersResponse.to_json( - eventarc.ListTriggersResponse() + return_value = eventarc.ListEnrollmentsResponse.to_json( + eventarc.ListEnrollmentsResponse() ) req.return_value.content = return_value - request = eventarc.ListTriggersRequest() + request = eventarc.ListEnrollmentsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = eventarc.ListTriggersResponse() + post.return_value = eventarc.ListEnrollmentsResponse() - client.list_triggers( + client.list_enrollments( request, metadata=[ ("key", "val"), @@ -13087,7 +30220,9 @@ def test_list_triggers_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_trigger_rest_bad_request(request_type=eventarc.CreateTriggerRequest): +def test_create_enrollment_rest_bad_request( + request_type=eventarc.CreateEnrollmentRequest, +): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13106,66 +30241,42 @@ def test_create_trigger_rest_bad_request(request_type=eventarc.CreateTriggerRequ response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.create_trigger(request) + client.create_enrollment(request) @pytest.mark.parametrize( "request_type", [ - eventarc.CreateTriggerRequest, + eventarc.CreateEnrollmentRequest, dict, ], ) -def test_create_trigger_rest_call_success(request_type): +def test_create_enrollment_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["trigger"] = { + request_init["enrollment"] = { "name": "name_value", "uid": "uid_value", + "etag": "etag_value", "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, - "event_filters": [ - { - "attribute": "attribute_value", - "value": "value_value", - "operator": "operator_value", - } - ], - "service_account": "service_account_value", - "destination": { - "cloud_run": { - "service": "service_value", - "path": "path_value", - "region": "region_value", - }, - "cloud_function": "cloud_function_value", - "gke": { - "cluster": "cluster_value", - "location": "location_value", - "namespace": "namespace_value", - "service": "service_value", - "path": "path_value", - }, - "workflow": "workflow_value", - }, - "transport": { - "pubsub": {"topic": "topic_value", "subscription": "subscription_value"} - }, "labels": {}, - "channel": "channel_value", - "conditions": {}, - "etag": "etag_value", + "annotations": {}, + "display_name": "display_name_value", + "cel_match": "cel_match_value", + "message_bus": "message_bus_value", + "destination": "destination_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 = eventarc.CreateTriggerRequest.meta.fields["trigger"] + test_field = eventarc.CreateEnrollmentRequest.meta.fields["enrollment"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13193,7 +30304,7 @@ def get_message_fields(field): # 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["trigger"].items(): # pragma: NO COVER + for field, value in request_init["enrollment"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13223,10 +30334,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["trigger"][field])): - del request_init["trigger"][field][i][subfield] + for i in range(0, len(request_init["enrollment"][field])): + del request_init["enrollment"][field][i][subfield] else: - del request_init["trigger"][field][subfield] + del request_init["enrollment"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -13240,14 +30351,14 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_trigger(request) + response = client.create_enrollment(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_trigger_rest_interceptors(null_interceptor): +def test_create_enrollment_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -13261,13 +30372,15 @@ def test_create_trigger_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EventarcRestInterceptor, "post_create_trigger" + transports.EventarcRestInterceptor, "post_create_enrollment" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_create_trigger" + transports.EventarcRestInterceptor, "pre_create_enrollment" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.CreateTriggerRequest.pb(eventarc.CreateTriggerRequest()) + pb_message = eventarc.CreateEnrollmentRequest.pb( + eventarc.CreateEnrollmentRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13280,7 +30393,7 @@ def test_create_trigger_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.CreateTriggerRequest() + request = eventarc.CreateEnrollmentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13288,7 +30401,7 @@ def test_create_trigger_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_trigger( + client.create_enrollment( request, metadata=[ ("key", "val"), @@ -13300,13 +30413,15 @@ def test_create_trigger_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_trigger_rest_bad_request(request_type=eventarc.UpdateTriggerRequest): +def test_update_enrollment_rest_bad_request( + request_type=eventarc.UpdateEnrollmentRequest, +): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "trigger": {"name": "projects/sample1/locations/sample2/triggers/sample3"} + "enrollment": {"name": "projects/sample1/locations/sample2/enrollments/sample3"} } request = request_type(**request_init) @@ -13321,68 +30436,44 @@ def test_update_trigger_rest_bad_request(request_type=eventarc.UpdateTriggerRequ response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.update_trigger(request) + client.update_enrollment(request) @pytest.mark.parametrize( "request_type", [ - eventarc.UpdateTriggerRequest, + eventarc.UpdateEnrollmentRequest, dict, ], ) -def test_update_trigger_rest_call_success(request_type): +def test_update_enrollment_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = { - "trigger": {"name": "projects/sample1/locations/sample2/triggers/sample3"} - } - request_init["trigger"] = { - "name": "projects/sample1/locations/sample2/triggers/sample3", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "event_filters": [ - { - "attribute": "attribute_value", - "value": "value_value", - "operator": "operator_value", - } - ], - "service_account": "service_account_value", - "destination": { - "cloud_run": { - "service": "service_value", - "path": "path_value", - "region": "region_value", - }, - "cloud_function": "cloud_function_value", - "gke": { - "cluster": "cluster_value", - "location": "location_value", - "namespace": "namespace_value", - "service": "service_value", - "path": "path_value", - }, - "workflow": "workflow_value", - }, - "transport": { - "pubsub": {"topic": "topic_value", "subscription": "subscription_value"} - }, - "labels": {}, - "channel": "channel_value", - "conditions": {}, + ) + + # send a request that will satisfy transcoding + request_init = { + "enrollment": {"name": "projects/sample1/locations/sample2/enrollments/sample3"} + } + request_init["enrollment"] = { + "name": "projects/sample1/locations/sample2/enrollments/sample3", + "uid": "uid_value", "etag": "etag_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "annotations": {}, + "display_name": "display_name_value", + "cel_match": "cel_match_value", + "message_bus": "message_bus_value", + "destination": "destination_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 = eventarc.UpdateTriggerRequest.meta.fields["trigger"] + test_field = eventarc.UpdateEnrollmentRequest.meta.fields["enrollment"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13410,7 +30501,7 @@ def get_message_fields(field): # 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["trigger"].items(): # pragma: NO COVER + for field, value in request_init["enrollment"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13440,10 +30531,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["trigger"][field])): - del request_init["trigger"][field][i][subfield] + for i in range(0, len(request_init["enrollment"][field])): + del request_init["enrollment"][field][i][subfield] else: - del request_init["trigger"][field][subfield] + del request_init["enrollment"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -13457,14 +30548,14 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_trigger(request) + response = client.update_enrollment(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_trigger_rest_interceptors(null_interceptor): +def test_update_enrollment_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -13478,13 +30569,15 @@ def test_update_trigger_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EventarcRestInterceptor, "post_update_trigger" + transports.EventarcRestInterceptor, "post_update_enrollment" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_update_trigger" + transports.EventarcRestInterceptor, "pre_update_enrollment" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.UpdateTriggerRequest.pb(eventarc.UpdateTriggerRequest()) + pb_message = eventarc.UpdateEnrollmentRequest.pb( + eventarc.UpdateEnrollmentRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13497,7 +30590,7 @@ def test_update_trigger_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.UpdateTriggerRequest() + request = eventarc.UpdateEnrollmentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13505,7 +30598,7 @@ def test_update_trigger_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_trigger( + client.update_enrollment( request, metadata=[ ("key", "val"), @@ -13517,12 +30610,14 @@ def test_update_trigger_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_trigger_rest_bad_request(request_type=eventarc.DeleteTriggerRequest): +def test_delete_enrollment_rest_bad_request( + request_type=eventarc.DeleteEnrollmentRequest, +): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/triggers/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/enrollments/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -13536,23 +30631,23 @@ def test_delete_trigger_rest_bad_request(request_type=eventarc.DeleteTriggerRequ response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.delete_trigger(request) + client.delete_enrollment(request) @pytest.mark.parametrize( "request_type", [ - eventarc.DeleteTriggerRequest, + eventarc.DeleteEnrollmentRequest, dict, ], ) -def test_delete_trigger_rest_call_success(request_type): +def test_delete_enrollment_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/triggers/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/enrollments/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -13566,14 +30661,14 @@ def test_delete_trigger_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_trigger(request) + response = client.delete_enrollment(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_trigger_rest_interceptors(null_interceptor): +def test_delete_enrollment_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -13587,13 +30682,15 @@ def test_delete_trigger_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EventarcRestInterceptor, "post_delete_trigger" + transports.EventarcRestInterceptor, "post_delete_enrollment" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_delete_trigger" + transports.EventarcRestInterceptor, "pre_delete_enrollment" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.DeleteTriggerRequest.pb(eventarc.DeleteTriggerRequest()) + pb_message = eventarc.DeleteEnrollmentRequest.pb( + eventarc.DeleteEnrollmentRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13606,7 +30703,7 @@ def test_delete_trigger_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.DeleteTriggerRequest() + request = eventarc.DeleteEnrollmentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13614,7 +30711,7 @@ def test_delete_trigger_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_trigger( + client.delete_enrollment( request, metadata=[ ("key", "val"), @@ -13626,12 +30723,12 @@ def test_delete_trigger_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_channel_rest_bad_request(request_type=eventarc.GetChannelRequest): +def test_get_pipeline_rest_bad_request(request_type=eventarc.GetPipelineRequest): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/pipelines/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -13645,36 +30742,34 @@ def test_get_channel_rest_bad_request(request_type=eventarc.GetChannelRequest): response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_channel(request) + client.get_pipeline(request) @pytest.mark.parametrize( "request_type", [ - eventarc.GetChannelRequest, + eventarc.GetPipelineRequest, dict, ], ) -def test_get_channel_rest_call_success(request_type): +def test_get_pipeline_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/pipelines/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 = channel.Channel( + return_value = pipeline.Pipeline( name="name_value", uid="uid_value", - provider="provider_value", - state=channel.Channel.State.PENDING, - activation_token="activation_token_value", + display_name="display_name_value", crypto_key_name="crypto_key_name_value", - pubsub_topic="pubsub_topic_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -13682,24 +30777,23 @@ def test_get_channel_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = channel.Channel.pb(return_value) + return_value = pipeline.Pipeline.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 - response = client.get_channel(request) + response = client.get_pipeline(request) # Establish that the response is the type that we expect. - assert isinstance(response, channel.Channel) + assert isinstance(response, pipeline.Pipeline) assert response.name == "name_value" assert response.uid == "uid_value" - assert response.provider == "provider_value" - assert response.state == channel.Channel.State.PENDING - assert response.activation_token == "activation_token_value" + assert response.display_name == "display_name_value" assert response.crypto_key_name == "crypto_key_name_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_channel_rest_interceptors(null_interceptor): +def test_get_pipeline_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -13711,13 +30805,13 @@ def test_get_channel_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EventarcRestInterceptor, "post_get_channel" + transports.EventarcRestInterceptor, "post_get_pipeline" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_get_channel" + transports.EventarcRestInterceptor, "pre_get_pipeline" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.GetChannelRequest.pb(eventarc.GetChannelRequest()) + pb_message = eventarc.GetPipelineRequest.pb(eventarc.GetPipelineRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13727,18 +30821,18 @@ def test_get_channel_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = channel.Channel.to_json(channel.Channel()) + return_value = pipeline.Pipeline.to_json(pipeline.Pipeline()) req.return_value.content = return_value - request = eventarc.GetChannelRequest() + request = eventarc.GetPipelineRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = channel.Channel() + post.return_value = pipeline.Pipeline() - client.get_channel( + client.get_pipeline( request, metadata=[ ("key", "val"), @@ -13750,7 +30844,7 @@ def test_get_channel_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_channels_rest_bad_request(request_type=eventarc.ListChannelsRequest): +def test_list_pipelines_rest_bad_request(request_type=eventarc.ListPipelinesRequest): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13769,17 +30863,17 @@ def test_list_channels_rest_bad_request(request_type=eventarc.ListChannelsReques response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_channels(request) + client.list_pipelines(request) @pytest.mark.parametrize( "request_type", [ - eventarc.ListChannelsRequest, + eventarc.ListPipelinesRequest, dict, ], ) -def test_list_channels_rest_call_success(request_type): +def test_list_pipelines_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13791,7 +30885,7 @@ def test_list_channels_rest_call_success(request_type): # 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 = eventarc.ListChannelsResponse( + return_value = eventarc.ListPipelinesResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -13801,20 +30895,20 @@ def test_list_channels_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = eventarc.ListChannelsResponse.pb(return_value) + return_value = eventarc.ListPipelinesResponse.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 - response = client.list_channels(request) + response = client.list_pipelines(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelsPager) + assert isinstance(response, pagers.ListPipelinesPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_channels_rest_interceptors(null_interceptor): +def test_list_pipelines_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -13826,13 +30920,13 @@ def test_list_channels_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EventarcRestInterceptor, "post_list_channels" + transports.EventarcRestInterceptor, "post_list_pipelines" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_list_channels" + transports.EventarcRestInterceptor, "pre_list_pipelines" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.ListChannelsRequest.pb(eventarc.ListChannelsRequest()) + pb_message = eventarc.ListPipelinesRequest.pb(eventarc.ListPipelinesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13842,20 +30936,20 @@ def test_list_channels_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = eventarc.ListChannelsResponse.to_json( - eventarc.ListChannelsResponse() + return_value = eventarc.ListPipelinesResponse.to_json( + eventarc.ListPipelinesResponse() ) req.return_value.content = return_value - request = eventarc.ListChannelsRequest() + request = eventarc.ListPipelinesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = eventarc.ListChannelsResponse() + post.return_value = eventarc.ListPipelinesResponse() - client.list_channels( + client.list_pipelines( request, metadata=[ ("key", "val"), @@ -13867,7 +30961,7 @@ def test_list_channels_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_channel_rest_bad_request(request_type=eventarc.CreateChannelRequest): +def test_create_pipeline_rest_bad_request(request_type=eventarc.CreatePipelineRequest): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13886,40 +30980,81 @@ def test_create_channel_rest_bad_request(request_type=eventarc.CreateChannelRequ response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.create_channel(request) + client.create_pipeline(request) @pytest.mark.parametrize( "request_type", [ - eventarc.CreateChannelRequest, + eventarc.CreatePipelineRequest, dict, ], ) -def test_create_channel_rest_call_success(request_type): +def test_create_pipeline_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["channel"] = { + request_init["pipeline"] = { "name": "name_value", - "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, - "provider": "provider_value", - "pubsub_topic": "pubsub_topic_value", - "state": 1, - "activation_token": "activation_token_value", + "labels": {}, + "uid": "uid_value", + "annotations": {}, + "display_name": "display_name_value", + "destinations": [ + { + "network_config": {"network_attachment": "network_attachment_value"}, + "http_endpoint": { + "uri": "uri_value", + "message_binding_template": "message_binding_template_value", + }, + "workflow": "workflow_value", + "message_bus": "message_bus_value", + "topic": "topic_value", + "authentication_config": { + "google_oidc": { + "service_account": "service_account_value", + "audience": "audience_value", + }, + "oauth_token": { + "service_account": "service_account_value", + "scope": "scope_value", + }, + }, + "output_payload_format": { + "protobuf": {"schema_definition": "schema_definition_value"}, + "avro": {"schema_definition": "schema_definition_value"}, + "json": {}, + }, + } + ], + "mediations": [ + { + "transformation": { + "transformation_template": "transformation_template_value" + } + } + ], "crypto_key_name": "crypto_key_name_value", + "input_payload_format": {}, + "logging_config": {"log_severity": 1}, + "retry_policy": { + "max_attempts": 1303, + "min_retry_delay": {"seconds": 751, "nanos": 543}, + "max_retry_delay": {}, + }, + "etag": "etag_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 = eventarc.CreateChannelRequest.meta.fields["channel"] + test_field = eventarc.CreatePipelineRequest.meta.fields["pipeline"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13947,7 +31082,7 @@ def get_message_fields(field): # 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["channel"].items(): # pragma: NO COVER + for field, value in request_init["pipeline"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13977,10 +31112,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["channel"][field])): - del request_init["channel"][field][i][subfield] + for i in range(0, len(request_init["pipeline"][field])): + del request_init["pipeline"][field][i][subfield] else: - del request_init["channel"][field][subfield] + del request_init["pipeline"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -13994,14 +31129,14 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_channel(request) + response = client.create_pipeline(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_channel_rest_interceptors(null_interceptor): +def test_create_pipeline_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -14015,13 +31150,13 @@ def test_create_channel_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EventarcRestInterceptor, "post_create_channel" + transports.EventarcRestInterceptor, "post_create_pipeline" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_create_channel" + transports.EventarcRestInterceptor, "pre_create_pipeline" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.CreateChannelRequest.pb(eventarc.CreateChannelRequest()) + pb_message = eventarc.CreatePipelineRequest.pb(eventarc.CreatePipelineRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14034,7 +31169,7 @@ def test_create_channel_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.CreateChannelRequest() + request = eventarc.CreatePipelineRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -14042,7 +31177,7 @@ def test_create_channel_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_channel( + client.create_pipeline( request, metadata=[ ("key", "val"), @@ -14054,13 +31189,13 @@ def test_create_channel_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_channel_rest_bad_request(request_type=eventarc.UpdateChannelRequest): +def test_update_pipeline_rest_bad_request(request_type=eventarc.UpdatePipelineRequest): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} + "pipeline": {"name": "projects/sample1/locations/sample2/pipelines/sample3"} } request = request_type(**request_init) @@ -14075,42 +31210,83 @@ def test_update_channel_rest_bad_request(request_type=eventarc.UpdateChannelRequ response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.update_channel(request) + client.update_pipeline(request) @pytest.mark.parametrize( "request_type", [ - eventarc.UpdateChannelRequest, + eventarc.UpdatePipelineRequest, dict, ], ) -def test_update_channel_rest_call_success(request_type): +def test_update_pipeline_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "channel": {"name": "projects/sample1/locations/sample2/channels/sample3"} + "pipeline": {"name": "projects/sample1/locations/sample2/pipelines/sample3"} } - request_init["channel"] = { - "name": "projects/sample1/locations/sample2/channels/sample3", - "uid": "uid_value", + request_init["pipeline"] = { + "name": "projects/sample1/locations/sample2/pipelines/sample3", "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, - "provider": "provider_value", - "pubsub_topic": "pubsub_topic_value", - "state": 1, - "activation_token": "activation_token_value", + "labels": {}, + "uid": "uid_value", + "annotations": {}, + "display_name": "display_name_value", + "destinations": [ + { + "network_config": {"network_attachment": "network_attachment_value"}, + "http_endpoint": { + "uri": "uri_value", + "message_binding_template": "message_binding_template_value", + }, + "workflow": "workflow_value", + "message_bus": "message_bus_value", + "topic": "topic_value", + "authentication_config": { + "google_oidc": { + "service_account": "service_account_value", + "audience": "audience_value", + }, + "oauth_token": { + "service_account": "service_account_value", + "scope": "scope_value", + }, + }, + "output_payload_format": { + "protobuf": {"schema_definition": "schema_definition_value"}, + "avro": {"schema_definition": "schema_definition_value"}, + "json": {}, + }, + } + ], + "mediations": [ + { + "transformation": { + "transformation_template": "transformation_template_value" + } + } + ], "crypto_key_name": "crypto_key_name_value", + "input_payload_format": {}, + "logging_config": {"log_severity": 1}, + "retry_policy": { + "max_attempts": 1303, + "min_retry_delay": {"seconds": 751, "nanos": 543}, + "max_retry_delay": {}, + }, + "etag": "etag_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 = eventarc.UpdateChannelRequest.meta.fields["channel"] + test_field = eventarc.UpdatePipelineRequest.meta.fields["pipeline"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -14138,7 +31314,7 @@ def get_message_fields(field): # 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["channel"].items(): # pragma: NO COVER + for field, value in request_init["pipeline"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14165,122 +31341,13 @@ def get_message_fields(field): 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["channel"][field])): - del request_init["channel"][field][i][subfield] - else: - del request_init["channel"][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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_channel(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_channel_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(transport=transport) - - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.EventarcRestInterceptor, "post_update_channel" - ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_update_channel" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdateChannelRequest.pb(eventarc.UpdateChannelRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = eventarc.UpdateChannelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_channel( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_channel_rest_bad_request(request_type=eventarc.DeleteChannelRequest): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/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 - client.delete_channel(request) - - -@pytest.mark.parametrize( - "request_type", - [ - eventarc.DeleteChannelRequest, - dict, - ], -) -def test_delete_channel_rest_call_success(request_type): - client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/channels/sample3"} + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["pipeline"][field])): + del request_init["pipeline"][field][i][subfield] + else: + del request_init["pipeline"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -14294,14 +31361,14 @@ def test_delete_channel_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_channel(request) + response = client.update_pipeline(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_channel_rest_interceptors(null_interceptor): +def test_update_pipeline_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -14315,13 +31382,13 @@ def test_delete_channel_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EventarcRestInterceptor, "post_delete_channel" + transports.EventarcRestInterceptor, "post_update_pipeline" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_delete_channel" + transports.EventarcRestInterceptor, "pre_update_pipeline" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.DeleteChannelRequest.pb(eventarc.DeleteChannelRequest()) + pb_message = eventarc.UpdatePipelineRequest.pb(eventarc.UpdatePipelineRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14334,7 +31401,7 @@ def test_delete_channel_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.DeleteChannelRequest() + request = eventarc.UpdatePipelineRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -14342,7 +31409,7 @@ def test_delete_channel_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_channel( + client.update_pipeline( request, metadata=[ ("key", "val"), @@ -14354,12 +31421,12 @@ def test_delete_channel_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_provider_rest_bad_request(request_type=eventarc.GetProviderRequest): +def test_delete_pipeline_rest_bad_request(request_type=eventarc.DeletePipelineRequest): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/providers/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/pipelines/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14373,52 +31440,44 @@ def test_get_provider_rest_bad_request(request_type=eventarc.GetProviderRequest) response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_provider(request) + client.delete_pipeline(request) @pytest.mark.parametrize( "request_type", [ - eventarc.GetProviderRequest, + eventarc.DeletePipelineRequest, dict, ], ) -def test_get_provider_rest_call_success(request_type): +def test_delete_pipeline_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/providers/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/pipelines/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 = discovery.Provider( - name="name_value", - display_name="display_name_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # 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 = discovery.Provider.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 - response = client.get_provider(request) + response = client.delete_pipeline(request) # Establish that the response is the type that we expect. - assert isinstance(response, discovery.Provider) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_provider_rest_interceptors(null_interceptor): +def test_delete_pipeline_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -14430,13 +31489,15 @@ def test_get_provider_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EventarcRestInterceptor, "post_get_provider" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_delete_pipeline" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_get_provider" + transports.EventarcRestInterceptor, "pre_delete_pipeline" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.GetProviderRequest.pb(eventarc.GetProviderRequest()) + pb_message = eventarc.DeletePipelineRequest.pb(eventarc.DeletePipelineRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14446,18 +31507,18 @@ def test_get_provider_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = discovery.Provider.to_json(discovery.Provider()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.GetProviderRequest() + request = eventarc.DeletePipelineRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = discovery.Provider() + post.return_value = operations_pb2.Operation() - client.get_provider( + client.delete_pipeline( request, metadata=[ ("key", "val"), @@ -14469,12 +31530,16 @@ def test_get_provider_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_providers_rest_bad_request(request_type=eventarc.ListProvidersRequest): +def test_get_google_api_source_rest_bad_request( + request_type=eventarc.GetGoogleApiSourceRequest, +): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "name": "projects/sample1/locations/sample2/googleApiSources/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14488,31 +31553,37 @@ def test_list_providers_rest_bad_request(request_type=eventarc.ListProvidersRequ response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_providers(request) + client.get_google_api_source(request) @pytest.mark.parametrize( "request_type", [ - eventarc.ListProvidersRequest, + eventarc.GetGoogleApiSourceRequest, dict, ], ) -def test_list_providers_rest_call_success(request_type): +def test_get_google_api_source_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "name": "projects/sample1/locations/sample2/googleApiSources/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 = eventarc.ListProvidersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = google_api_source.GoogleApiSource( + name="name_value", + uid="uid_value", + etag="etag_value", + display_name="display_name_value", + destination="destination_value", + crypto_key_name="crypto_key_name_value", ) # Wrap the value into a proper Response obj @@ -14520,20 +31591,24 @@ def test_list_providers_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = eventarc.ListProvidersResponse.pb(return_value) + return_value = google_api_source.GoogleApiSource.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 - response = client.list_providers(request) + response = client.get_google_api_source(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProvidersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, google_api_source.GoogleApiSource) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.etag == "etag_value" + assert response.display_name == "display_name_value" + assert response.destination == "destination_value" + assert response.crypto_key_name == "crypto_key_name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_providers_rest_interceptors(null_interceptor): +def test_get_google_api_source_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -14545,13 +31620,15 @@ def test_list_providers_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EventarcRestInterceptor, "post_list_providers" + transports.EventarcRestInterceptor, "post_get_google_api_source" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_list_providers" + transports.EventarcRestInterceptor, "pre_get_google_api_source" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.ListProvidersRequest.pb(eventarc.ListProvidersRequest()) + pb_message = eventarc.GetGoogleApiSourceRequest.pb( + eventarc.GetGoogleApiSourceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14561,20 +31638,20 @@ def test_list_providers_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = eventarc.ListProvidersResponse.to_json( - eventarc.ListProvidersResponse() + return_value = google_api_source.GoogleApiSource.to_json( + google_api_source.GoogleApiSource() ) req.return_value.content = return_value - request = eventarc.ListProvidersRequest() + request = eventarc.GetGoogleApiSourceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = eventarc.ListProvidersResponse() + post.return_value = google_api_source.GoogleApiSource() - client.list_providers( + client.get_google_api_source( request, metadata=[ ("key", "val"), @@ -14586,16 +31663,14 @@ def test_list_providers_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_channel_connection_rest_bad_request( - request_type=eventarc.GetChannelConnectionRequest, +def test_list_google_api_sources_rest_bad_request( + request_type=eventarc.ListGoogleApiSourcesRequest, ): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/channelConnections/sample3" - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14609,35 +31684,31 @@ def test_get_channel_connection_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.get_channel_connection(request) + client.list_google_api_sources(request) @pytest.mark.parametrize( "request_type", [ - eventarc.GetChannelConnectionRequest, + eventarc.ListGoogleApiSourcesRequest, dict, ], ) -def test_get_channel_connection_rest_call_success(request_type): +def test_list_google_api_sources_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/channelConnections/sample3" - } + request_init = {"parent": "projects/sample1/locations/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 = channel_connection.ChannelConnection( - name="name_value", - uid="uid_value", - channel="channel_value", - activation_token="activation_token_value", + return_value = eventarc.ListGoogleApiSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj @@ -14645,22 +31716,20 @@ def test_get_channel_connection_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = channel_connection.ChannelConnection.pb(return_value) + return_value = eventarc.ListGoogleApiSourcesResponse.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 - response = client.get_channel_connection(request) + response = client.list_google_api_sources(request) # Establish that the response is the type that we expect. - assert isinstance(response, channel_connection.ChannelConnection) - assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.channel == "channel_value" - assert response.activation_token == "activation_token_value" + assert isinstance(response, pagers.ListGoogleApiSourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_channel_connection_rest_interceptors(null_interceptor): +def test_list_google_api_sources_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -14672,14 +31741,14 @@ def test_get_channel_connection_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EventarcRestInterceptor, "post_get_channel_connection" + transports.EventarcRestInterceptor, "post_list_google_api_sources" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_get_channel_connection" + transports.EventarcRestInterceptor, "pre_list_google_api_sources" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.GetChannelConnectionRequest.pb( - eventarc.GetChannelConnectionRequest() + pb_message = eventarc.ListGoogleApiSourcesRequest.pb( + eventarc.ListGoogleApiSourcesRequest() ) transcode.return_value = { "method": "post", @@ -14690,20 +31759,20 @@ def test_get_channel_connection_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = channel_connection.ChannelConnection.to_json( - channel_connection.ChannelConnection() + return_value = eventarc.ListGoogleApiSourcesResponse.to_json( + eventarc.ListGoogleApiSourcesResponse() ) req.return_value.content = return_value - request = eventarc.GetChannelConnectionRequest() + request = eventarc.ListGoogleApiSourcesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = channel_connection.ChannelConnection() + post.return_value = eventarc.ListGoogleApiSourcesResponse() - client.get_channel_connection( + client.list_google_api_sources( request, metadata=[ ("key", "val"), @@ -14715,8 +31784,8 @@ def test_get_channel_connection_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_channel_connections_rest_bad_request( - request_type=eventarc.ListChannelConnectionsRequest, +def test_create_google_api_source_rest_bad_request( + request_type=eventarc.CreateGoogleApiSourceRequest, ): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -14736,52 +31805,124 @@ def test_list_channel_connections_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.list_channel_connections(request) + client.create_google_api_source(request) @pytest.mark.parametrize( "request_type", [ - eventarc.ListChannelConnectionsRequest, + eventarc.CreateGoogleApiSourceRequest, dict, ], ) -def test_list_channel_connections_rest_call_success(request_type): +def test_create_google_api_source_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["google_api_source"] = { + "name": "name_value", + "uid": "uid_value", + "etag": "etag_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "annotations": {}, + "display_name": "display_name_value", + "destination": "destination_value", + "crypto_key_name": "crypto_key_name_value", + "logging_config": {"log_severity": 1}, + } + # 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 = eventarc.CreateGoogleApiSourceRequest.meta.fields["google_api_source"] + + 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["google_api_source"].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["google_api_source"][field])): + del request_init["google_api_source"][field][i][subfield] + else: + del request_init["google_api_source"][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 = eventarc.ListChannelConnectionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # 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 = eventarc.ListChannelConnectionsResponse.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 - response = client.list_channel_connections(request) + response = client.create_google_api_source(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelConnectionsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_channel_connections_rest_interceptors(null_interceptor): +def test_create_google_api_source_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -14793,14 +31934,16 @@ def test_list_channel_connections_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EventarcRestInterceptor, "post_list_channel_connections" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EventarcRestInterceptor, "post_create_google_api_source" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_list_channel_connections" + transports.EventarcRestInterceptor, "pre_create_google_api_source" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.ListChannelConnectionsRequest.pb( - eventarc.ListChannelConnectionsRequest() + pb_message = eventarc.CreateGoogleApiSourceRequest.pb( + eventarc.CreateGoogleApiSourceRequest() ) transcode.return_value = { "method": "post", @@ -14811,20 +31954,18 @@ def test_list_channel_connections_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = eventarc.ListChannelConnectionsResponse.to_json( - eventarc.ListChannelConnectionsResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.ListChannelConnectionsRequest() + request = eventarc.CreateGoogleApiSourceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = eventarc.ListChannelConnectionsResponse() + post.return_value = operations_pb2.Operation() - client.list_channel_connections( + client.create_google_api_source( request, metadata=[ ("key", "val"), @@ -14836,14 +31977,18 @@ def test_list_channel_connections_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_channel_connection_rest_bad_request( - request_type=eventarc.CreateChannelConnectionRequest, +def test_update_google_api_source_rest_bad_request( + request_type=eventarc.UpdateGoogleApiSourceRequest, ): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "google_api_source": { + "name": "projects/sample1/locations/sample2/googleApiSources/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14857,39 +32002,46 @@ def test_create_channel_connection_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.create_channel_connection(request) + client.update_google_api_source(request) @pytest.mark.parametrize( "request_type", [ - eventarc.CreateChannelConnectionRequest, + eventarc.UpdateGoogleApiSourceRequest, dict, ], ) -def test_create_channel_connection_rest_call_success(request_type): +def test_update_google_api_source_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["channel_connection"] = { - "name": "name_value", + request_init = { + "google_api_source": { + "name": "projects/sample1/locations/sample2/googleApiSources/sample3" + } + } + request_init["google_api_source"] = { + "name": "projects/sample1/locations/sample2/googleApiSources/sample3", "uid": "uid_value", - "channel": "channel_value", + "etag": "etag_value", "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, - "activation_token": "activation_token_value", + "labels": {}, + "annotations": {}, + "display_name": "display_name_value", + "destination": "destination_value", + "crypto_key_name": "crypto_key_name_value", + "logging_config": {"log_severity": 1}, } # 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 = eventarc.CreateChannelConnectionRequest.meta.fields[ - "channel_connection" - ] + test_field = eventarc.UpdateGoogleApiSourceRequest.meta.fields["google_api_source"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -14917,7 +32069,7 @@ def get_message_fields(field): # 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["channel_connection"].items(): # pragma: NO COVER + for field, value in request_init["google_api_source"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -14947,10 +32099,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["channel_connection"][field])): - del request_init["channel_connection"][field][i][subfield] + for i in range(0, len(request_init["google_api_source"][field])): + del request_init["google_api_source"][field][i][subfield] else: - del request_init["channel_connection"][field][subfield] + del request_init["google_api_source"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -14964,14 +32116,14 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_channel_connection(request) + response = client.update_google_api_source(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_channel_connection_rest_interceptors(null_interceptor): +def test_update_google_api_source_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -14985,14 +32137,14 @@ def test_create_channel_connection_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EventarcRestInterceptor, "post_create_channel_connection" + transports.EventarcRestInterceptor, "post_update_google_api_source" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_create_channel_connection" + transports.EventarcRestInterceptor, "pre_update_google_api_source" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.CreateChannelConnectionRequest.pb( - eventarc.CreateChannelConnectionRequest() + pb_message = eventarc.UpdateGoogleApiSourceRequest.pb( + eventarc.UpdateGoogleApiSourceRequest() ) transcode.return_value = { "method": "post", @@ -15006,7 +32158,7 @@ def test_create_channel_connection_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.CreateChannelConnectionRequest() + request = eventarc.UpdateGoogleApiSourceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -15014,7 +32166,7 @@ def test_create_channel_connection_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_channel_connection( + client.update_google_api_source( request, metadata=[ ("key", "val"), @@ -15026,15 +32178,15 @@ def test_create_channel_connection_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_channel_connection_rest_bad_request( - request_type=eventarc.DeleteChannelConnectionRequest, +def test_delete_google_api_source_rest_bad_request( + request_type=eventarc.DeleteGoogleApiSourceRequest, ): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/channelConnections/sample3" + "name": "projects/sample1/locations/sample2/googleApiSources/sample3" } request = request_type(**request_init) @@ -15049,24 +32201,24 @@ def test_delete_channel_connection_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.delete_channel_connection(request) + client.delete_google_api_source(request) @pytest.mark.parametrize( "request_type", [ - eventarc.DeleteChannelConnectionRequest, + eventarc.DeleteGoogleApiSourceRequest, dict, ], ) -def test_delete_channel_connection_rest_call_success(request_type): +def test_delete_google_api_source_rest_call_success(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/channelConnections/sample3" + "name": "projects/sample1/locations/sample2/googleApiSources/sample3" } request = request_type(**request_init) @@ -15081,14 +32233,14 @@ def test_delete_channel_connection_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_channel_connection(request) + response = client.delete_google_api_source(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_channel_connection_rest_interceptors(null_interceptor): +def test_delete_google_api_source_rest_interceptors(null_interceptor): transport = transports.EventarcRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), @@ -15102,14 +32254,14 @@ def test_delete_channel_connection_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EventarcRestInterceptor, "post_delete_channel_connection" + transports.EventarcRestInterceptor, "post_delete_google_api_source" ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_delete_channel_connection" + transports.EventarcRestInterceptor, "pre_delete_google_api_source" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = eventarc.DeleteChannelConnectionRequest.pb( - eventarc.DeleteChannelConnectionRequest() + pb_message = eventarc.DeleteGoogleApiSourceRequest.pb( + eventarc.DeleteGoogleApiSourceRequest() ) transcode.return_value = { "method": "post", @@ -15123,360 +32275,452 @@ def test_delete_channel_connection_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = eventarc.DeleteChannelConnectionRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + request = eventarc.DeleteGoogleApiSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_google_api_source( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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 = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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 = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/triggers/sample3"}, request + ) + + # 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 = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/triggers/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/triggers/sample3"}, request + ) + + # 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 = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/triggers/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value - client.delete_channel_connection( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + response = client.set_iam_policy(request) - pre.assert_called_once() - post.assert_called_once() + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) -def test_get_google_channel_config_rest_bad_request( - request_type=eventarc.GetGoogleChannelConfigRequest, +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/triggers/sample3"}, request ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/googleChannelConfig"} - 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() + response_value = Response() json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = mock.Mock() + response_value.request = Request() req.return_value = response_value - client.get_google_channel_config(request) + client.test_iam_permissions(request) @pytest.mark.parametrize( "request_type", [ - eventarc.GetGoogleChannelConfigRequest, + iam_policy_pb2.TestIamPermissionsRequest, dict, ], ) -def test_get_google_channel_config_rest_call_success(request_type): +def test_test_iam_permissions_rest(request_type): client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/googleChannelConfig"} + request_init = {"resource": "projects/sample1/locations/sample2/triggers/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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = google_channel_config.GoogleChannelConfig( - name="name_value", - crypto_key_name="crypto_key_name_value", - ) + return_value = iam_policy_pb2.TestIamPermissionsResponse() # 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 = google_channel_config.GoogleChannelConfig.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 - response = client.get_google_channel_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, google_channel_config.GoogleChannelConfig) - assert response.name == "name_value" - assert response.crypto_key_name == "crypto_key_name_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_google_channel_config_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), - ) - client = EventarcClient(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.EventarcRestInterceptor, "post_get_google_channel_config" - ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_get_google_channel_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.GetGoogleChannelConfigRequest.pb( - eventarc.GetGoogleChannelConfigRequest() - ) - 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 - return_value = google_channel_config.GoogleChannelConfig.to_json( - google_channel_config.GoogleChannelConfig() - ) - req.return_value.content = return_value - request = eventarc.GetGoogleChannelConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = google_channel_config.GoogleChannelConfig() + req.return_value = response_value - client.get_google_channel_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + response = client.test_iam_permissions(request) - pre.assert_called_once() - post.assert_called_once() + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) -def test_update_google_channel_config_rest_bad_request( - request_type=eventarc.UpdateGoogleChannelConfigRequest, +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, ): client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - # send a request that will satisfy transcoding - request_init = { - "google_channel_config": { - "name": "projects/sample1/locations/sample2/googleChannelConfig" - } - } - 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() + response_value = Response() json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = mock.Mock() + response_value.request = Request() req.return_value = response_value - client.update_google_channel_config(request) + client.cancel_operation(request) @pytest.mark.parametrize( "request_type", [ - eventarc.UpdateGoogleChannelConfigRequest, + operations_pb2.CancelOperationRequest, dict, ], ) -def test_update_google_channel_config_rest_call_success(request_type): +def test_cancel_operation_rest(request_type): client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "google_channel_config": { - "name": "projects/sample1/locations/sample2/googleChannelConfig" - } - } - request_init["google_channel_config"] = { - "name": "projects/sample1/locations/sample2/googleChannelConfig", - "update_time": {"seconds": 751, "nanos": 543}, - "crypto_key_name": "crypto_key_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 = eventarc.UpdateGoogleChannelConfigRequest.meta.fields[ - "google_channel_config" - ] - - 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[ - "google_channel_config" - ].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["google_channel_config"][field])): - del request_init["google_channel_config"][field][i][subfield] - else: - del request_init["google_channel_config"][field][subfield] + request_init = {"name": "projects/sample1/locations/sample2/operations/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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = gce_google_channel_config.GoogleChannelConfig( - name="name_value", - crypto_key_name="crypto_key_name_value", - ) + return_value = None # 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 = gce_google_channel_config.GoogleChannelConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "{}" response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value - response = client.update_google_channel_config(request) + + response = client.cancel_operation(request) # Establish that the response is the type that we expect. - assert isinstance(response, gce_google_channel_config.GoogleChannelConfig) - assert response.name == "name_value" - assert response.crypto_key_name == "crypto_key_name_value" + assert response is None -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_google_channel_config_rest_interceptors(null_interceptor): - transport = transports.EventarcRestTransport( +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EventarcRestInterceptor(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - client = EventarcClient(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.EventarcRestInterceptor, "post_update_google_channel_config" - ) as post, mock.patch.object( - transports.EventarcRestInterceptor, "pre_update_google_channel_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = eventarc.UpdateGoogleChannelConfigRequest.pb( - eventarc.UpdateGoogleChannelConfigRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + # 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 = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = gce_google_channel_config.GoogleChannelConfig.to_json( - gce_google_channel_config.GoogleChannelConfig() - ) - req.return_value.content = return_value - request = eventarc.UpdateGoogleChannelConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gce_google_channel_config.GoogleChannelConfig() +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - client.update_google_channel_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) # Mock the http request call within the method and fake a BadRequest error. @@ -15490,28 +32734,28 @@ def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationReq response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_location(request) + client.get_operation(request) @pytest.mark.parametrize( "request_type", [ - locations_pb2.GetLocationRequest, + operations_pb2.GetOperationRequest, dict, ], ) -def test_get_location_rest(request_type): +def test_get_operation_rest(request_type): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -15521,21 +32765,23 @@ def test_get_location_rest(request_type): req.return_value = response_value - response = client.get_location(request) + response = client.get_operation(request) # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) + assert isinstance(response, operations_pb2.Operation) -def test_list_locations_rest_bad_request( - request_type=locations_pb2.ListLocationsRequest, +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, ): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( @@ -15548,735 +32794,761 @@ def test_list_locations_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_locations(request) + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = EventarcClient( + 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_trigger_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_trigger), "__call__") as call: + client.get_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetTriggerRequest() + + 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_triggers_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_triggers), "__call__") as call: + client.list_triggers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListTriggersRequest() + + 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_create_trigger_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_trigger), "__call__") as call: + client.create_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateTriggerRequest() + + 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_trigger_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_trigger), "__call__") as call: + client.update_trigger(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateTriggerRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.ListLocationsRequest, - dict, - ], -) -def test_list_locations_rest(request_type): + +# 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_trigger_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_trigger), "__call__") as call: + client.delete_trigger(request=None) - response = client.list_locations(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteTriggerRequest() - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) + assert args[0] == request_msg -def test_get_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.GetIamPolicyRequest, -): +# 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_channel_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"resource": "projects/sample1/locations/sample2/triggers/sample3"}, request - ) - # 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 = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_channel), "__call__") as call: + client.get_channel(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.GetIamPolicyRequest, - dict, - ], -) -def test_get_iam_policy_rest(request_type): + +# 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_channels_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"resource": "projects/sample1/locations/sample2/triggers/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_channels), "__call__") as call: + client.list_channels(request=None) - response = client.get_iam_policy(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelsRequest() - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) + assert args[0] == request_msg -def test_set_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.SetIamPolicyRequest, -): +# 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_create_channel_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"resource": "projects/sample1/locations/sample2/triggers/sample3"}, request - ) - # 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 = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: + client.create_channel(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelRequest() -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest, - dict, - ], -) -def test_set_iam_policy_rest(request_type): + 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_channel_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"resource": "projects/sample1/locations/sample2/triggers/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_channel), "__call__") as call: + client.update_channel(request=None) - response = client.set_iam_policy(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateChannelRequest() - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) + assert args[0] == request_msg -def test_test_iam_permissions_rest_bad_request( - request_type=iam_policy_pb2.TestIamPermissionsRequest, -): +# 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_channel_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"resource": "projects/sample1/locations/sample2/triggers/sample3"}, request - ) - # 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 = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: + client.delete_channel(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelRequest() -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, - ], -) -def test_test_iam_permissions_rest(request_type): + 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_provider_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"resource": "projects/sample1/locations/sample2/triggers/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_provider), "__call__") as call: + client.get_provider(request=None) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetProviderRequest() - req.return_value = response_value + assert args[0] == request_msg - response = client.test_iam_permissions(request) - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) +# 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_providers_empty_call_rest(): + client = EventarcClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_providers), "__call__") as call: + client.list_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListProvidersRequest() + assert args[0] == request_msg -def test_cancel_operation_rest_bad_request( - request_type=operations_pb2.CancelOperationRequest, -): + +# 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_channel_connection_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # 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 = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_connection), "__call__" + ) as call: + client.get_channel_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetChannelConnectionRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.CancelOperationRequest, - dict, - ], -) -def test_cancel_operation_rest(request_type): + +# 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_channel_connections_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = "{}" - response_value.content = json_return_value.encode("UTF-8") - - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_connections), "__call__" + ) as call: + client.list_channel_connections(request=None) - response = client.cancel_operation(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListChannelConnectionsRequest() - # Establish that the response is the type that we expect. - assert response is None + assert args[0] == request_msg -def test_delete_operation_rest_bad_request( - request_type=operations_pb2.DeleteOperationRequest, -): +# 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_create_channel_connection_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # 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 = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_connection), "__call__" + ) as call: + client.create_channel_connection(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.CreateChannelConnectionRequest() -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): + 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_channel_connection_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = "{}" - response_value.content = json_return_value.encode("UTF-8") - - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_connection), "__call__" + ) as call: + client.delete_channel_connection(request=None) - response = client.delete_operation(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.DeleteChannelConnectionRequest() - # Establish that the response is the type that we expect. - assert response is None + assert args[0] == request_msg -def test_get_operation_rest_bad_request( - request_type=operations_pb2.GetOperationRequest, -): +# 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_google_channel_config_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # 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 = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_google_channel_config), "__call__" + ) as call: + client.get_google_channel_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetGoogleChannelConfigRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): + +# 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_google_channel_config_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_google_channel_config), "__call__" + ) as call: + client.update_google_channel_config(request=None) - response = client.get_operation(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.UpdateGoogleChannelConfigRequest() - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + assert args[0] == request_msg -def test_list_operations_rest_bad_request( - request_type=operations_pb2.ListOperationsRequest, -): +# 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_message_bus_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - # 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 = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_message_bus), "__call__") as call: + client.get_message_bus(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.GetMessageBusRequest() -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): + 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_message_buses_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_buses), "__call__" + ) as call: + client.list_message_buses(request=None) - response = client.list_operations(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusesRequest() - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + assert args[0] == request_msg -def test_initialize_client_w_rest(): +# 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_message_bus_enrollments_empty_call_rest(): client = EventarcClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert client is not None + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_bus_enrollments), "__call__" + ) as call: + client.list_message_bus_enrollments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = eventarc.ListMessageBusEnrollmentsRequest() + + 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_trigger_empty_call_rest(): +def test_create_message_bus_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_trigger), "__call__") as call: - client.get_trigger(request=None) + with mock.patch.object( + type(client.transport.create_message_bus), "__call__" + ) as call: + client.create_message_bus(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetTriggerRequest() + request_msg = eventarc.CreateMessageBusRequest() 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_triggers_empty_call_rest(): +def test_update_message_bus_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_triggers), "__call__") as call: - client.list_triggers(request=None) + with mock.patch.object( + type(client.transport.update_message_bus), "__call__" + ) as call: + client.update_message_bus(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListTriggersRequest() + request_msg = eventarc.UpdateMessageBusRequest() 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_create_trigger_empty_call_rest(): +def test_delete_message_bus_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_trigger), "__call__") as call: - client.create_trigger(request=None) + with mock.patch.object( + type(client.transport.delete_message_bus), "__call__" + ) as call: + client.delete_message_bus(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateTriggerRequest() + request_msg = eventarc.DeleteMessageBusRequest() 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_trigger_empty_call_rest(): +def test_get_enrollment_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_trigger), "__call__") as call: - client.update_trigger(request=None) + with mock.patch.object(type(client.transport.get_enrollment), "__call__") as call: + client.get_enrollment(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateTriggerRequest() + request_msg = eventarc.GetEnrollmentRequest() 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_trigger_empty_call_rest(): +def test_list_enrollments_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_trigger), "__call__") as call: - client.delete_trigger(request=None) + with mock.patch.object(type(client.transport.list_enrollments), "__call__") as call: + client.list_enrollments(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteTriggerRequest() + request_msg = eventarc.ListEnrollmentsRequest() 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_channel_empty_call_rest(): +def test_create_enrollment_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_channel), "__call__") as call: - client.get_channel(request=None) + with mock.patch.object( + type(client.transport.create_enrollment), "__call__" + ) as call: + client.create_enrollment(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelRequest() + request_msg = eventarc.CreateEnrollmentRequest() 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_channels_empty_call_rest(): +def test_update_enrollment_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_channels), "__call__") as call: - client.list_channels(request=None) + with mock.patch.object( + type(client.transport.update_enrollment), "__call__" + ) as call: + client.update_enrollment(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelsRequest() + request_msg = eventarc.UpdateEnrollmentRequest() 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_create_channel_empty_call_rest(): +def test_delete_enrollment_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_channel_), "__call__") as call: - client.create_channel(request=None) + with mock.patch.object( + type(client.transport.delete_enrollment), "__call__" + ) as call: + client.delete_enrollment(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelRequest() + request_msg = eventarc.DeleteEnrollmentRequest() 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_channel_empty_call_rest(): +def test_get_pipeline_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_channel), "__call__") as call: - client.update_channel(request=None) + with mock.patch.object(type(client.transport.get_pipeline), "__call__") as call: + client.get_pipeline(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateChannelRequest() + request_msg = eventarc.GetPipelineRequest() 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_channel_empty_call_rest(): +def test_list_pipelines_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_channel), "__call__") as call: - client.delete_channel(request=None) + with mock.patch.object(type(client.transport.list_pipelines), "__call__") as call: + client.list_pipelines(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelRequest() + request_msg = eventarc.ListPipelinesRequest() 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_provider_empty_call_rest(): +def test_create_pipeline_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_provider), "__call__") as call: - client.get_provider(request=None) + with mock.patch.object(type(client.transport.create_pipeline), "__call__") as call: + client.create_pipeline(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetProviderRequest() + request_msg = eventarc.CreatePipelineRequest() 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_providers_empty_call_rest(): +def test_update_pipeline_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_providers), "__call__") as call: - client.list_providers(request=None) + with mock.patch.object(type(client.transport.update_pipeline), "__call__") as call: + client.update_pipeline(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListProvidersRequest() + request_msg = eventarc.UpdatePipelineRequest() 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_channel_connection_empty_call_rest(): +def test_delete_pipeline_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_channel_connection), "__call__" - ) as call: - client.get_channel_connection(request=None) + with mock.patch.object(type(client.transport.delete_pipeline), "__call__") as call: + client.delete_pipeline(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetChannelConnectionRequest() + request_msg = eventarc.DeletePipelineRequest() 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_channel_connections_empty_call_rest(): +def test_get_google_api_source_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16284,21 +33556,21 @@ def test_list_channel_connections_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_channel_connections), "__call__" + type(client.transport.get_google_api_source), "__call__" ) as call: - client.list_channel_connections(request=None) + client.get_google_api_source(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.ListChannelConnectionsRequest() + request_msg = eventarc.GetGoogleApiSourceRequest() 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_create_channel_connection_empty_call_rest(): +def test_list_google_api_sources_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16306,21 +33578,21 @@ def test_create_channel_connection_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_channel_connection), "__call__" + type(client.transport.list_google_api_sources), "__call__" ) as call: - client.create_channel_connection(request=None) + client.list_google_api_sources(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.CreateChannelConnectionRequest() + request_msg = eventarc.ListGoogleApiSourcesRequest() 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_channel_connection_empty_call_rest(): +def test_create_google_api_source_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16328,21 +33600,21 @@ def test_delete_channel_connection_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_connection), "__call__" + type(client.transport.create_google_api_source), "__call__" ) as call: - client.delete_channel_connection(request=None) + client.create_google_api_source(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.DeleteChannelConnectionRequest() + request_msg = eventarc.CreateGoogleApiSourceRequest() 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_google_channel_config_empty_call_rest(): +def test_update_google_api_source_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16350,21 +33622,21 @@ def test_get_google_channel_config_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_google_channel_config), "__call__" + type(client.transport.update_google_api_source), "__call__" ) as call: - client.get_google_channel_config(request=None) + client.update_google_api_source(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.GetGoogleChannelConfigRequest() + request_msg = eventarc.UpdateGoogleApiSourceRequest() 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_google_channel_config_empty_call_rest(): +def test_delete_google_api_source_empty_call_rest(): client = EventarcClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16372,14 +33644,14 @@ def test_update_google_channel_config_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_google_channel_config), "__call__" + type(client.transport.delete_google_api_source), "__call__" ) as call: - client.update_google_channel_config(request=None) + client.delete_google_api_source(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = eventarc.UpdateGoogleChannelConfigRequest() + request_msg = eventarc.DeleteGoogleApiSourceRequest() assert args[0] == request_msg @@ -16452,6 +33724,27 @@ def test_eventarc_base_transport(): "delete_channel_connection", "get_google_channel_config", "update_google_channel_config", + "get_message_bus", + "list_message_buses", + "list_message_bus_enrollments", + "create_message_bus", + "update_message_bus", + "delete_message_bus", + "get_enrollment", + "list_enrollments", + "create_enrollment", + "update_enrollment", + "delete_enrollment", + "get_pipeline", + "list_pipelines", + "create_pipeline", + "update_pipeline", + "delete_pipeline", + "get_google_api_source", + "list_google_api_sources", + "create_google_api_source", + "update_google_api_source", + "delete_google_api_source", "set_iam_policy", "get_iam_policy", "test_iam_permissions", @@ -16775,6 +34068,69 @@ def test_eventarc_client_transport_session_collision(transport_name): session1 = client1.transport.update_google_channel_config._session session2 = client2.transport.update_google_channel_config._session assert session1 != session2 + session1 = client1.transport.get_message_bus._session + session2 = client2.transport.get_message_bus._session + assert session1 != session2 + session1 = client1.transport.list_message_buses._session + session2 = client2.transport.list_message_buses._session + assert session1 != session2 + session1 = client1.transport.list_message_bus_enrollments._session + session2 = client2.transport.list_message_bus_enrollments._session + assert session1 != session2 + session1 = client1.transport.create_message_bus._session + session2 = client2.transport.create_message_bus._session + assert session1 != session2 + session1 = client1.transport.update_message_bus._session + session2 = client2.transport.update_message_bus._session + assert session1 != session2 + session1 = client1.transport.delete_message_bus._session + session2 = client2.transport.delete_message_bus._session + assert session1 != session2 + session1 = client1.transport.get_enrollment._session + session2 = client2.transport.get_enrollment._session + assert session1 != session2 + session1 = client1.transport.list_enrollments._session + session2 = client2.transport.list_enrollments._session + assert session1 != session2 + session1 = client1.transport.create_enrollment._session + session2 = client2.transport.create_enrollment._session + assert session1 != session2 + session1 = client1.transport.update_enrollment._session + session2 = client2.transport.update_enrollment._session + assert session1 != session2 + session1 = client1.transport.delete_enrollment._session + session2 = client2.transport.delete_enrollment._session + assert session1 != session2 + session1 = client1.transport.get_pipeline._session + session2 = client2.transport.get_pipeline._session + assert session1 != session2 + session1 = client1.transport.list_pipelines._session + session2 = client2.transport.list_pipelines._session + assert session1 != session2 + session1 = client1.transport.create_pipeline._session + session2 = client2.transport.create_pipeline._session + assert session1 != session2 + session1 = client1.transport.update_pipeline._session + session2 = client2.transport.update_pipeline._session + assert session1 != session2 + session1 = client1.transport.delete_pipeline._session + session2 = client2.transport.delete_pipeline._session + assert session1 != session2 + session1 = client1.transport.get_google_api_source._session + session2 = client2.transport.get_google_api_source._session + assert session1 != session2 + session1 = client1.transport.list_google_api_sources._session + session2 = client2.transport.list_google_api_sources._session + assert session1 != session2 + session1 = client1.transport.create_google_api_source._session + session2 = client2.transport.create_google_api_source._session + assert session1 != session2 + session1 = client1.transport.update_google_api_source._session + session2 = client2.transport.update_google_api_source._session + assert session1 != session2 + session1 = client1.transport.delete_google_api_source._session + session2 = client2.transport.delete_google_api_source._session + assert session1 != session2 def test_eventarc_grpc_transport_channel(): @@ -17038,6 +34394,60 @@ def test_parse_crypto_key_path(): assert expected == actual +def test_enrollment_path(): + project = "whelk" + location = "octopus" + enrollment = "oyster" + expected = ( + "projects/{project}/locations/{location}/enrollments/{enrollment}".format( + project=project, + location=location, + enrollment=enrollment, + ) + ) + actual = EventarcClient.enrollment_path(project, location, enrollment) + assert expected == actual + + +def test_parse_enrollment_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "enrollment": "mussel", + } + path = EventarcClient.enrollment_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_enrollment_path(path) + assert expected == actual + + +def test_google_api_source_path(): + project = "winkle" + location = "nautilus" + google_api_source = "scallop" + expected = "projects/{project}/locations/{location}/googleApiSources/{google_api_source}".format( + project=project, + location=location, + google_api_source=google_api_source, + ) + actual = EventarcClient.google_api_source_path(project, location, google_api_source) + assert expected == actual + + +def test_parse_google_api_source_path(): + expected = { + "project": "abalone", + "location": "squid", + "google_api_source": "clam", + } + path = EventarcClient.google_api_source_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_google_api_source_path(path) + assert expected == actual + + def test_google_channel_config_path(): project = "whelk" location = "octopus" @@ -17061,10 +34471,90 @@ def test_parse_google_channel_config_path(): assert expected == actual -def test_provider_path(): +def test_message_bus_path(): + project = "cuttlefish" + location = "mussel" + message_bus = "winkle" + expected = ( + "projects/{project}/locations/{location}/messageBuses/{message_bus}".format( + project=project, + location=location, + message_bus=message_bus, + ) + ) + actual = EventarcClient.message_bus_path(project, location, message_bus) + assert expected == actual + + +def test_parse_message_bus_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "message_bus": "abalone", + } + path = EventarcClient.message_bus_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_message_bus_path(path) + assert expected == actual + + +def test_network_attachment_path(): + project = "squid" + region = "clam" + networkattachment = "whelk" + expected = "projects/{project}/regions/{region}/networkAttachments/{networkattachment}".format( + project=project, + region=region, + networkattachment=networkattachment, + ) + actual = EventarcClient.network_attachment_path(project, region, networkattachment) + assert expected == actual + + +def test_parse_network_attachment_path(): + expected = { + "project": "octopus", + "region": "oyster", + "networkattachment": "nudibranch", + } + path = EventarcClient.network_attachment_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_network_attachment_path(path) + assert expected == actual + + +def test_pipeline_path(): project = "cuttlefish" location = "mussel" - provider = "winkle" + pipeline = "winkle" + expected = "projects/{project}/locations/{location}/pipelines/{pipeline}".format( + project=project, + location=location, + pipeline=pipeline, + ) + actual = EventarcClient.pipeline_path(project, location, pipeline) + assert expected == actual + + +def test_parse_pipeline_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "pipeline": "abalone", + } + path = EventarcClient.pipeline_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_pipeline_path(path) + assert expected == actual + + +def test_provider_path(): + project = "squid" + location = "clam" + provider = "whelk" expected = "projects/{project}/locations/{location}/providers/{provider}".format( project=project, location=location, @@ -17076,9 +34566,9 @@ def test_provider_path(): def test_parse_provider_path(): expected = { - "project": "nautilus", - "location": "scallop", - "provider": "abalone", + "project": "octopus", + "location": "oyster", + "provider": "nudibranch", } path = EventarcClient.provider_path(**expected) @@ -17103,8 +34593,8 @@ def test_parse_service_path(): def test_service_account_path(): - project = "squid" - service_account = "clam" + project = "cuttlefish" + service_account = "mussel" expected = "projects/{project}/serviceAccounts/{service_account}".format( project=project, service_account=service_account, @@ -17115,8 +34605,8 @@ def test_service_account_path(): def test_parse_service_account_path(): expected = { - "project": "whelk", - "service_account": "octopus", + "project": "winkle", + "service_account": "nautilus", } path = EventarcClient.service_account_path(**expected) @@ -17125,10 +34615,33 @@ def test_parse_service_account_path(): assert expected == actual +def test_topic_path(): + project = "scallop" + topic = "abalone" + expected = "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) + actual = EventarcClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "squid", + "topic": "clam", + } + path = EventarcClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = EventarcClient.parse_topic_path(path) + assert expected == actual + + def test_trigger_path(): - project = "oyster" - location = "nudibranch" - trigger = "cuttlefish" + project = "whelk" + location = "octopus" + trigger = "oyster" expected = "projects/{project}/locations/{location}/triggers/{trigger}".format( project=project, location=location, @@ -17140,9 +34653,9 @@ def test_trigger_path(): def test_parse_trigger_path(): expected = { - "project": "mussel", - "location": "winkle", - "trigger": "nautilus", + "project": "nudibranch", + "location": "cuttlefish", + "trigger": "mussel", } path = EventarcClient.trigger_path(**expected) @@ -17152,9 +34665,9 @@ def test_parse_trigger_path(): def test_workflow_path(): - project = "scallop" - location = "abalone" - workflow = "squid" + project = "winkle" + location = "nautilus" + workflow = "scallop" expected = "projects/{project}/locations/{location}/workflows/{workflow}".format( project=project, location=location, @@ -17166,9 +34679,9 @@ def test_workflow_path(): def test_parse_workflow_path(): expected = { - "project": "clam", - "location": "whelk", - "workflow": "octopus", + "project": "abalone", + "location": "squid", + "workflow": "clam", } path = EventarcClient.workflow_path(**expected) @@ -17178,7 +34691,7 @@ def test_parse_workflow_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -17188,7 +34701,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "octopus", } path = EventarcClient.common_billing_account_path(**expected) @@ -17198,7 +34711,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "oyster" expected = "folders/{folder}".format( folder=folder, ) @@ -17208,7 +34721,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "nudibranch", } path = EventarcClient.common_folder_path(**expected) @@ -17218,7 +34731,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "cuttlefish" expected = "organizations/{organization}".format( organization=organization, ) @@ -17228,7 +34741,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "mussel", } path = EventarcClient.common_organization_path(**expected) @@ -17238,7 +34751,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "winkle" expected = "projects/{project}".format( project=project, ) @@ -17248,7 +34761,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "nautilus", } path = EventarcClient.common_project_path(**expected) @@ -17258,8 +34771,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -17270,8 +34783,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "squid", + "location": "clam", } path = EventarcClient.common_location_path(**expected) diff --git a/packages/google-cloud-quotas/CHANGELOG.md b/packages/google-cloud-quotas/CHANGELOG.md index 3fb645469463..9cc3fc87916f 100644 --- a/packages/google-cloud-quotas/CHANGELOG.md +++ b/packages/google-cloud-quotas/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-quotas-v0.1.11...google-cloud-quotas-v0.1.12) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([59c4287](https://github.com/googleapis/google-cloud-python/commit/59c42878386ee08d1717b73e47d33d76cfb38ba0)) + ## [0.1.11](https://github.com/googleapis/google-cloud-python/compare/google-cloud-quotas-v0.1.10...google-cloud-quotas-v0.1.11) (2024-10-24) diff --git a/packages/google-cloud-quotas/google/cloud/cloudquotas/gapic_version.py b/packages/google-cloud-quotas/google/cloud/cloudquotas/gapic_version.py index 4b834789ba9e..17bbab4c1877 100644 --- a/packages/google-cloud-quotas/google/cloud/cloudquotas/gapic_version.py +++ b/packages/google-cloud-quotas/google/cloud/cloudquotas/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.11" # {x-release-please-version} +__version__ = "0.1.12" # {x-release-please-version} diff --git a/packages/google-cloud-quotas/google/cloud/cloudquotas_v1/gapic_version.py b/packages/google-cloud-quotas/google/cloud/cloudquotas_v1/gapic_version.py index 4b834789ba9e..17bbab4c1877 100644 --- a/packages/google-cloud-quotas/google/cloud/cloudquotas_v1/gapic_version.py +++ b/packages/google-cloud-quotas/google/cloud/cloudquotas_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.11" # {x-release-please-version} +__version__ = "0.1.12" # {x-release-please-version} diff --git a/packages/google-cloud-quotas/google/cloud/cloudquotas_v1/services/cloud_quotas/client.py b/packages/google-cloud-quotas/google/cloud/cloudquotas_v1/services/cloud_quotas/client.py index 81a992db5567..5dfd44f40594 100644 --- a/packages/google-cloud-quotas/google/cloud/cloudquotas_v1/services/cloud_quotas/client.py +++ b/packages/google-cloud-quotas/google/cloud/cloudquotas_v1/services/cloud_quotas/client.py @@ -496,36 +496,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = CloudQuotasClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -535,13 +505,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or CloudQuotasClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-quotas/samples/generated_samples/snippet_metadata_google.api.cloudquotas.v1.json b/packages/google-cloud-quotas/samples/generated_samples/snippet_metadata_google.api.cloudquotas.v1.json index 6b5a5b89ef0f..8480a91a1fb8 100644 --- a/packages/google-cloud-quotas/samples/generated_samples/snippet_metadata_google.api.cloudquotas.v1.json +++ b/packages/google-cloud-quotas/samples/generated_samples/snippet_metadata_google.api.cloudquotas.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-quotas", - "version": "0.1.11" + "version": "0.1.12" }, "snippets": [ { diff --git a/packages/google-cloud-quotas/tests/unit/gapic/cloudquotas_v1/test_cloud_quotas.py b/packages/google-cloud-quotas/tests/unit/gapic/cloudquotas_v1/test_cloud_quotas.py index 3af4f1a44e43..789a5a86bafe 100644 --- a/packages/google-cloud-quotas/tests/unit/gapic/cloudquotas_v1/test_cloud_quotas.py +++ b/packages/google-cloud-quotas/tests/unit/gapic/cloudquotas_v1/test_cloud_quotas.py @@ -302,86 +302,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (CloudQuotasClient, transports.CloudQuotasGrpcTransport, "grpc"), - (CloudQuotasClient, transports.CloudQuotasRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md b/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md index c8cc00398424..cd823730ad15 100644 --- a/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md +++ b/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [1.24.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-recaptcha-enterprise-v1.23.0...google-cloud-recaptcha-enterprise-v1.24.0) (2024-10-31) + + +### Features + +* enable Akamai web application firewall ([81bf6fe](https://github.com/googleapis/google-cloud-python/commit/81bf6fe826181c729ec756756d1bf315914a8fc4)) +* support for ListIpOverrides and RemoveIpOverride ([81bf6fe](https://github.com/googleapis/google-cloud-python/commit/81bf6fe826181c729ec756756d1bf315914a8fc4)) + + +### Documentation + +* minor updates to reference documentation ([81bf6fe](https://github.com/googleapis/google-cloud-python/commit/81bf6fe826181c729ec756756d1bf315914a8fc4)) + ## [1.23.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-recaptcha-enterprise-v1.22.1...google-cloud-recaptcha-enterprise-v1.23.0) (2024-10-24) diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/__init__.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/__init__.py index 74085402cea4..cab44f14d8ed 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/__init__.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/__init__.py @@ -57,6 +57,8 @@ Key, ListFirewallPoliciesRequest, ListFirewallPoliciesResponse, + ListIpOverridesRequest, + ListIpOverridesResponse, ListKeysRequest, ListKeysResponse, ListRelatedAccountGroupMembershipsRequest, @@ -69,6 +71,8 @@ PrivatePasswordLeakVerification, RelatedAccountGroup, RelatedAccountGroupMembership, + RemoveIpOverrideRequest, + RemoveIpOverrideResponse, ReorderFirewallPoliciesRequest, ReorderFirewallPoliciesResponse, RetrieveLegacySecretKeyRequest, @@ -126,6 +130,8 @@ "Key", "ListFirewallPoliciesRequest", "ListFirewallPoliciesResponse", + "ListIpOverridesRequest", + "ListIpOverridesResponse", "ListKeysRequest", "ListKeysResponse", "ListRelatedAccountGroupMembershipsRequest", @@ -138,6 +144,8 @@ "PrivatePasswordLeakVerification", "RelatedAccountGroup", "RelatedAccountGroupMembership", + "RemoveIpOverrideRequest", + "RemoveIpOverrideResponse", "ReorderFirewallPoliciesRequest", "ReorderFirewallPoliciesResponse", "RetrieveLegacySecretKeyRequest", diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/gapic_version.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/gapic_version.py index c8313abd74cb..45f4e360312c 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/gapic_version.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.23.0" # {x-release-please-version} +__version__ = "1.24.0" # {x-release-please-version} diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/__init__.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/__init__.py index 872b50ab387a..648463089928 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/__init__.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/__init__.py @@ -55,6 +55,8 @@ Key, ListFirewallPoliciesRequest, ListFirewallPoliciesResponse, + ListIpOverridesRequest, + ListIpOverridesResponse, ListKeysRequest, ListKeysResponse, ListRelatedAccountGroupMembershipsRequest, @@ -67,6 +69,8 @@ PrivatePasswordLeakVerification, RelatedAccountGroup, RelatedAccountGroupMembership, + RemoveIpOverrideRequest, + RemoveIpOverrideResponse, ReorderFirewallPoliciesRequest, ReorderFirewallPoliciesResponse, RetrieveLegacySecretKeyRequest, @@ -123,6 +127,8 @@ "Key", "ListFirewallPoliciesRequest", "ListFirewallPoliciesResponse", + "ListIpOverridesRequest", + "ListIpOverridesResponse", "ListKeysRequest", "ListKeysResponse", "ListRelatedAccountGroupMembershipsRequest", @@ -136,6 +142,8 @@ "RecaptchaEnterpriseServiceClient", "RelatedAccountGroup", "RelatedAccountGroupMembership", + "RemoveIpOverrideRequest", + "RemoveIpOverrideResponse", "ReorderFirewallPoliciesRequest", "ReorderFirewallPoliciesResponse", "RetrieveLegacySecretKeyRequest", diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_metadata.json b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_metadata.json index 8722f66f3086..fc9061dcda44 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_metadata.json +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_metadata.json @@ -65,6 +65,11 @@ "list_firewall_policies" ] }, + "ListIpOverrides": { + "methods": [ + "list_ip_overrides" + ] + }, "ListKeys": { "methods": [ "list_keys" @@ -85,6 +90,11 @@ "migrate_key" ] }, + "RemoveIpOverride": { + "methods": [ + "remove_ip_override" + ] + }, "ReorderFirewallPolicies": { "methods": [ "reorder_firewall_policies" @@ -170,6 +180,11 @@ "list_firewall_policies" ] }, + "ListIpOverrides": { + "methods": [ + "list_ip_overrides" + ] + }, "ListKeys": { "methods": [ "list_keys" @@ -190,6 +205,11 @@ "migrate_key" ] }, + "RemoveIpOverride": { + "methods": [ + "remove_ip_override" + ] + }, "ReorderFirewallPolicies": { "methods": [ "reorder_firewall_policies" diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_version.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_version.py index c8313abd74cb..45f4e360312c 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_version.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.23.0" # {x-release-please-version} +__version__ = "1.24.0" # {x-release-please-version} diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py index 1ae940ad5ff1..4350a7dc29ac 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py @@ -705,7 +705,7 @@ async def sample_list_keys(): The request object. The list keys request message. parent (:class:`str`): Required. The name of the project that contains the keys - that are listed, in the format ``projects/{project}``. + that is listed, in the format ``projects/{project}``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1424,6 +1424,256 @@ async def sample_add_ip_override(): # Done; return the response. return response + async def remove_ip_override( + self, + request: Optional[ + Union[recaptchaenterprise.RemoveIpOverrideRequest, dict] + ] = None, + *, + name: Optional[str] = None, + ip_override_data: Optional[recaptchaenterprise.IpOverrideData] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recaptchaenterprise.RemoveIpOverrideResponse: + r"""Removes an IP override from a key. The following restrictions + hold: + + - If the IP isn't found in an existing IP override, a + ``NOT_FOUND`` error is returned. + - If the IP is found in an existing IP override, but the + override type does not match, a ``NOT_FOUND`` error is + returned. + + .. 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 recaptchaenterprise_v1 + + async def sample_remove_ip_override(): + # Create a client + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceAsyncClient() + + # Initialize request argument(s) + ip_override_data = recaptchaenterprise_v1.IpOverrideData() + ip_override_data.ip = "ip_value" + ip_override_data.override_type = "ALLOW" + + request = recaptchaenterprise_v1.RemoveIpOverrideRequest( + name="name_value", + ip_override_data=ip_override_data, + ) + + # Make the request + response = await client.remove_ip_override(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recaptchaenterprise_v1.types.RemoveIpOverrideRequest, dict]]): + The request object. The removeIpOverride request message. + name (:class:`str`): + Required. The name of the key from which the IP override + is removed, in the format + ``projects/{project}/keys/{key}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ip_override_data (:class:`google.cloud.recaptchaenterprise_v1.types.IpOverrideData`): + Required. IP override to be removed + from the key. + + This corresponds to the ``ip_override_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.types.RemoveIpOverrideResponse: + Response for RemoveIpOverride. + """ + # 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. + has_flattened_params = any([name, ip_override_data]) + 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, recaptchaenterprise.RemoveIpOverrideRequest): + request = recaptchaenterprise.RemoveIpOverrideRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ip_override_data is not None: + request.ip_override_data = ip_override_data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.remove_ip_override + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_ip_overrides( + self, + request: Optional[ + Union[recaptchaenterprise.ListIpOverridesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIpOverridesAsyncPager: + r"""Lists all IP overrides for a key. + + .. 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 recaptchaenterprise_v1 + + async def sample_list_ip_overrides(): + # Create a client + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceAsyncClient() + + # Initialize request argument(s) + request = recaptchaenterprise_v1.ListIpOverridesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ip_overrides(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.recaptchaenterprise_v1.types.ListIpOverridesRequest, dict]]): + The request object. The ListIpOverrides request message. + parent (:class:`str`): + Required. The parent key for which the IP overrides are + listed, in the format ``projects/{project}/keys/{key}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.pagers.ListIpOverridesAsyncPager: + Response for ListIpOverrides. + + 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. + has_flattened_params = any([parent]) + 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, recaptchaenterprise.ListIpOverridesRequest): + request = recaptchaenterprise.ListIpOverridesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_ip_overrides + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListIpOverridesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_metrics( self, request: Optional[Union[recaptchaenterprise.GetMetricsRequest, dict]] = None, @@ -1575,7 +1825,7 @@ async def sample_create_firewall_policy(): The request object. The create firewall policy request message. parent (:class:`str`): - Required. The name of the project this policy will apply + Required. The name of the project this policy applies to, in the format ``projects/{project}``. This corresponds to the ``parent`` field diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py index bd62b5ca1e8c..90e133f2dacc 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py @@ -1181,7 +1181,7 @@ def sample_list_keys(): The request object. The list keys request message. parent (str): Required. The name of the project that contains the keys - that are listed, in the format ``projects/{project}``. + that is listed, in the format ``projects/{project}``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1884,6 +1884,250 @@ def sample_add_ip_override(): # Done; return the response. return response + def remove_ip_override( + self, + request: Optional[ + Union[recaptchaenterprise.RemoveIpOverrideRequest, dict] + ] = None, + *, + name: Optional[str] = None, + ip_override_data: Optional[recaptchaenterprise.IpOverrideData] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recaptchaenterprise.RemoveIpOverrideResponse: + r"""Removes an IP override from a key. The following restrictions + hold: + + - If the IP isn't found in an existing IP override, a + ``NOT_FOUND`` error is returned. + - If the IP is found in an existing IP override, but the + override type does not match, a ``NOT_FOUND`` error is + returned. + + .. 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 recaptchaenterprise_v1 + + def sample_remove_ip_override(): + # Create a client + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Initialize request argument(s) + ip_override_data = recaptchaenterprise_v1.IpOverrideData() + ip_override_data.ip = "ip_value" + ip_override_data.override_type = "ALLOW" + + request = recaptchaenterprise_v1.RemoveIpOverrideRequest( + name="name_value", + ip_override_data=ip_override_data, + ) + + # Make the request + response = client.remove_ip_override(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.recaptchaenterprise_v1.types.RemoveIpOverrideRequest, dict]): + The request object. The removeIpOverride request message. + name (str): + Required. The name of the key from which the IP override + is removed, in the format + ``projects/{project}/keys/{key}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ip_override_data (google.cloud.recaptchaenterprise_v1.types.IpOverrideData): + Required. IP override to be removed + from the key. + + This corresponds to the ``ip_override_data`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.types.RemoveIpOverrideResponse: + Response for RemoveIpOverride. + """ + # 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. + has_flattened_params = any([name, ip_override_data]) + 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, recaptchaenterprise.RemoveIpOverrideRequest): + request = recaptchaenterprise.RemoveIpOverrideRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ip_override_data is not None: + request.ip_override_data = ip_override_data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_ip_override] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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_ip_overrides( + self, + request: Optional[ + Union[recaptchaenterprise.ListIpOverridesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIpOverridesPager: + r"""Lists all IP overrides for a key. + + .. 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 recaptchaenterprise_v1 + + def sample_list_ip_overrides(): + # Create a client + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Initialize request argument(s) + request = recaptchaenterprise_v1.ListIpOverridesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ip_overrides(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.recaptchaenterprise_v1.types.ListIpOverridesRequest, dict]): + The request object. The ListIpOverrides request message. + parent (str): + Required. The parent key for which the IP overrides are + listed, in the format ``projects/{project}/keys/{key}``. + + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.pagers.ListIpOverridesPager: + Response for ListIpOverrides. + + 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. + has_flattened_params = any([parent]) + 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, recaptchaenterprise.ListIpOverridesRequest): + request = recaptchaenterprise.ListIpOverridesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_ip_overrides] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListIpOverridesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def get_metrics( self, request: Optional[Union[recaptchaenterprise.GetMetricsRequest, dict]] = None, @@ -2032,7 +2276,7 @@ def sample_create_firewall_policy(): The request object. The create firewall policy request message. parent (str): - Required. The name of the project this policy will apply + Required. The name of the project this policy applies to, in the format ``projects/{project}``. This corresponds to the ``parent`` field diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/pagers.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/pagers.py index 7f66f86b07f5..f50c54e13244 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/pagers.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/pagers.py @@ -193,6 +193,158 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListIpOverridesPager: + """A pager for iterating through ``list_ip_overrides`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recaptchaenterprise_v1.types.ListIpOverridesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``ip_overrides`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIpOverrides`` requests and continue to iterate + through the ``ip_overrides`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recaptchaenterprise_v1.types.ListIpOverridesResponse` + 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[..., recaptchaenterprise.ListIpOverridesResponse], + request: recaptchaenterprise.ListIpOverridesRequest, + response: recaptchaenterprise.ListIpOverridesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.recaptchaenterprise_v1.types.ListIpOverridesRequest): + The initial request object. + response (google.cloud.recaptchaenterprise_v1.types.ListIpOverridesResponse): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recaptchaenterprise.ListIpOverridesRequest(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[recaptchaenterprise.ListIpOverridesResponse]: + 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[recaptchaenterprise.IpOverrideData]: + for page in self.pages: + yield from page.ip_overrides + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListIpOverridesAsyncPager: + """A pager for iterating through ``list_ip_overrides`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recaptchaenterprise_v1.types.ListIpOverridesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``ip_overrides`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIpOverrides`` requests and continue to iterate + through the ``ip_overrides`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recaptchaenterprise_v1.types.ListIpOverridesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[recaptchaenterprise.ListIpOverridesResponse]], + request: recaptchaenterprise.ListIpOverridesRequest, + response: recaptchaenterprise.ListIpOverridesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.recaptchaenterprise_v1.types.ListIpOverridesRequest): + The initial request object. + response (google.cloud.recaptchaenterprise_v1.types.ListIpOverridesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = recaptchaenterprise.ListIpOverridesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[recaptchaenterprise.ListIpOverridesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[recaptchaenterprise.IpOverrideData]: + async def async_generator(): + async for page in self.pages: + for response in page.ip_overrides: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListFirewallPoliciesPager: """A pager for iterating through ``list_firewall_policies`` requests. diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/base.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/base.py index 1d997dedd2b7..0da7cf8f3ec3 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/base.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/base.py @@ -179,6 +179,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.remove_ip_override: gapic_v1.method.wrap_method( + self.remove_ip_override, + default_timeout=None, + client_info=client_info, + ), + self.list_ip_overrides: gapic_v1.method.wrap_method( + self.list_ip_overrides, + default_timeout=None, + client_info=client_info, + ), self.get_metrics: gapic_v1.method.wrap_method( self.get_metrics, default_timeout=None, @@ -344,6 +354,30 @@ def add_ip_override( ]: raise NotImplementedError() + @property + def remove_ip_override( + self, + ) -> Callable[ + [recaptchaenterprise.RemoveIpOverrideRequest], + Union[ + recaptchaenterprise.RemoveIpOverrideResponse, + Awaitable[recaptchaenterprise.RemoveIpOverrideResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_ip_overrides( + self, + ) -> Callable[ + [recaptchaenterprise.ListIpOverridesRequest], + Union[ + recaptchaenterprise.ListIpOverridesResponse, + Awaitable[recaptchaenterprise.ListIpOverridesResponse], + ], + ]: + raise NotImplementedError() + @property def get_metrics( self, diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py index bb598e78465f..687afe06080c 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py @@ -524,6 +524,71 @@ def add_ip_override( ) return self._stubs["add_ip_override"] + @property + def remove_ip_override( + self, + ) -> Callable[ + [recaptchaenterprise.RemoveIpOverrideRequest], + recaptchaenterprise.RemoveIpOverrideResponse, + ]: + r"""Return a callable for the remove ip override method over gRPC. + + Removes an IP override from a key. The following restrictions + hold: + + - If the IP isn't found in an existing IP override, a + ``NOT_FOUND`` error is returned. + - If the IP is found in an existing IP override, but the + override type does not match, a ``NOT_FOUND`` error is + returned. + + Returns: + Callable[[~.RemoveIpOverrideRequest], + ~.RemoveIpOverrideResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_ip_override" not in self._stubs: + self._stubs["remove_ip_override"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/RemoveIpOverride", + request_serializer=recaptchaenterprise.RemoveIpOverrideRequest.serialize, + response_deserializer=recaptchaenterprise.RemoveIpOverrideResponse.deserialize, + ) + return self._stubs["remove_ip_override"] + + @property + def list_ip_overrides( + self, + ) -> Callable[ + [recaptchaenterprise.ListIpOverridesRequest], + recaptchaenterprise.ListIpOverridesResponse, + ]: + r"""Return a callable for the list ip overrides method over gRPC. + + Lists all IP overrides for a key. + + Returns: + Callable[[~.ListIpOverridesRequest], + ~.ListIpOverridesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_ip_overrides" not in self._stubs: + self._stubs["list_ip_overrides"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/ListIpOverrides", + request_serializer=recaptchaenterprise.ListIpOverridesRequest.serialize, + response_deserializer=recaptchaenterprise.ListIpOverridesResponse.deserialize, + ) + return self._stubs["list_ip_overrides"] + @property def get_metrics( self, diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py index 1de0e29e087c..d1ca99fffd9b 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py @@ -544,6 +544,71 @@ def add_ip_override( ) return self._stubs["add_ip_override"] + @property + def remove_ip_override( + self, + ) -> Callable[ + [recaptchaenterprise.RemoveIpOverrideRequest], + Awaitable[recaptchaenterprise.RemoveIpOverrideResponse], + ]: + r"""Return a callable for the remove ip override method over gRPC. + + Removes an IP override from a key. The following restrictions + hold: + + - If the IP isn't found in an existing IP override, a + ``NOT_FOUND`` error is returned. + - If the IP is found in an existing IP override, but the + override type does not match, a ``NOT_FOUND`` error is + returned. + + Returns: + Callable[[~.RemoveIpOverrideRequest], + Awaitable[~.RemoveIpOverrideResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_ip_override" not in self._stubs: + self._stubs["remove_ip_override"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/RemoveIpOverride", + request_serializer=recaptchaenterprise.RemoveIpOverrideRequest.serialize, + response_deserializer=recaptchaenterprise.RemoveIpOverrideResponse.deserialize, + ) + return self._stubs["remove_ip_override"] + + @property + def list_ip_overrides( + self, + ) -> Callable[ + [recaptchaenterprise.ListIpOverridesRequest], + Awaitable[recaptchaenterprise.ListIpOverridesResponse], + ]: + r"""Return a callable for the list ip overrides method over gRPC. + + Lists all IP overrides for a key. + + Returns: + Callable[[~.ListIpOverridesRequest], + Awaitable[~.ListIpOverridesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_ip_overrides" not in self._stubs: + self._stubs["list_ip_overrides"] = self.grpc_channel.unary_unary( + "/google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService/ListIpOverrides", + request_serializer=recaptchaenterprise.ListIpOverridesRequest.serialize, + response_deserializer=recaptchaenterprise.ListIpOverridesResponse.deserialize, + ) + return self._stubs["list_ip_overrides"] + @property def get_metrics( self, @@ -895,6 +960,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.remove_ip_override: self._wrap_method( + self.remove_ip_override, + default_timeout=None, + client_info=client_info, + ), + self.list_ip_overrides: self._wrap_method( + self.list_ip_overrides, + default_timeout=None, + client_info=client_info, + ), self.get_metrics: self._wrap_method( self.get_metrics, default_timeout=None, diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/__init__.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/__init__.py index 230f8d821762..21b3c2cfa07e 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/__init__.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/__init__.py @@ -46,6 +46,8 @@ Key, ListFirewallPoliciesRequest, ListFirewallPoliciesResponse, + ListIpOverridesRequest, + ListIpOverridesResponse, ListKeysRequest, ListKeysResponse, ListRelatedAccountGroupMembershipsRequest, @@ -58,6 +60,8 @@ PrivatePasswordLeakVerification, RelatedAccountGroup, RelatedAccountGroupMembership, + RemoveIpOverrideRequest, + RemoveIpOverrideResponse, ReorderFirewallPoliciesRequest, ReorderFirewallPoliciesResponse, RetrieveLegacySecretKeyRequest, @@ -113,6 +117,8 @@ "Key", "ListFirewallPoliciesRequest", "ListFirewallPoliciesResponse", + "ListIpOverridesRequest", + "ListIpOverridesResponse", "ListKeysRequest", "ListKeysResponse", "ListRelatedAccountGroupMembershipsRequest", @@ -125,6 +131,8 @@ "PrivatePasswordLeakVerification", "RelatedAccountGroup", "RelatedAccountGroupMembership", + "RemoveIpOverrideRequest", + "RemoveIpOverrideResponse", "ReorderFirewallPoliciesRequest", "ReorderFirewallPoliciesResponse", "RetrieveLegacySecretKeyRequest", diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py index 129df8657cdd..2683e3f38156 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py @@ -84,6 +84,10 @@ "SearchRelatedAccountGroupMembershipsResponse", "AddIpOverrideRequest", "AddIpOverrideResponse", + "RemoveIpOverrideRequest", + "RemoveIpOverrideResponse", + "ListIpOverridesRequest", + "ListIpOverridesResponse", "RelatedAccountGroupMembership", "RelatedAccountGroup", "WafSettings", @@ -786,7 +790,7 @@ class Event(proto.Message): express (bool): Optional. Flag for a reCAPTCHA express request for an assessment without a token. If enabled, ``site_key`` must - reference an express key. + reference an Express site key. requested_uri (str): Optional. The URI resource the user requested that triggered an assessment. @@ -808,9 +812,9 @@ class Event(proto.Message): transaction_data (google.cloud.recaptchaenterprise_v1.types.TransactionData): Optional. Data describing a payment transaction to be assessed. Sending this data - enables reCAPTCHA Fraud Prevention and the - FraudPreventionAssessment component in the - response. + enables reCAPTCHA Enterprise Fraud Prevention + and the FraudPreventionAssessment component in + the response. user_info (google.cloud.recaptchaenterprise_v1.types.UserInfo): Optional. Information about the user that generates this event, when they can be @@ -1766,7 +1770,7 @@ class ListKeysRequest(proto.Message): Attributes: parent (str): Required. The name of the project that contains the keys - that are listed, in the format ``projects/{project}``. + that is listed, in the format ``projects/{project}``. page_size (int): Optional. The maximum number of keys to return. Default is 10. Max limit is 1000. @@ -1889,8 +1893,8 @@ class CreateFirewallPolicyRequest(proto.Message): Attributes: parent (str): - Required. The name of the project this policy will apply to, - in the format ``projects/{project}``. + Required. The name of the project this policy applies to, in + the format ``projects/{project}``. firewall_policy (google.cloud.recaptchaenterprise_v1.types.FirewallPolicy): Required. Information to create the policy. """ @@ -2106,8 +2110,8 @@ class Metrics(proto.Message): challenge_metrics (MutableSequence[google.cloud.recaptchaenterprise_v1.types.ChallengeMetrics]): Metrics are continuous and in order by dates, and in the granularity of day. Only - challenge-based keys (CHECKBOX, INVISIBLE), will - have challenge-based data. + challenge-based keys (CHECKBOX, INVISIBLE) have + challenge-based data. """ name: str = proto.Field( @@ -2185,8 +2189,8 @@ class Key(proto.Message): This field is a member of `oneof`_ ``platform_settings``. express_settings (google.cloud.recaptchaenterprise_v1.types.ExpressKeySettings): - Settings specific to keys that can be used - for reCAPTCHA Express. + Settings for keys that can be used by + reCAPTCHA Express. This field is a member of `oneof`_ ``platform_settings``. labels (MutableMapping[str, str]): @@ -2261,15 +2265,14 @@ class TestingOptions(proto.Message): Attributes: testing_score (float): - Optional. All assessments for this Key will - return this score. Must be between 0 (likely not + Optional. All assessments for this Key return + this score. Must be between 0 (likely not legitimate) and 1 (likely legitimate) inclusive. testing_challenge (google.cloud.recaptchaenterprise_v1.types.TestingOptions.TestingChallenge): Optional. For challenge-based keys only (CHECKBOX, INVISIBLE), all challenge requests - for this site will return nocaptcha if - NOCAPTCHA, or an unsolvable challenge if - CHALLENGE. + for this site return nocaptcha if NOCAPTCHA, or + an unsolvable challenge if CHALLENGE. """ class TestingChallenge(proto.Enum): @@ -2308,8 +2311,8 @@ class WebKeySettings(proto.Message): Attributes: allow_all_domains (bool): - Optional. If set to true, it means allowed_domains will not - be enforced. + Optional. If set to true, it means allowed_domains are not + enforced. allowed_domains (MutableSequence[str]): Optional. Domains or subdomains of websites allowed to use the key. All subdomains of an @@ -2327,10 +2330,10 @@ class WebKeySettings(proto.Message): Required. Describes how this key is integrated with the website. challenge_security_preference (google.cloud.recaptchaenterprise_v1.types.WebKeySettings.ChallengeSecurityPreference): - Optional. Settings for the frequency and - difficulty at which this key triggers captcha - challenges. This should only be specified for - IntegrationTypes CHECKBOX and INVISIBLE. + Optional. Settings for the frequency and difficulty at which + this key triggers captcha challenges. This should only be + specified for IntegrationTypes CHECKBOX and INVISIBLE and + SCORE_AND_CHALLENGE. """ class IntegrationType(proto.Enum): @@ -2451,12 +2454,11 @@ class IOSKeySettings(proto.Message): apple_developer_id (google.cloud.recaptchaenterprise_v1.types.AppleDeveloperId): Optional. Apple Developer account details for the app that is protected by the reCAPTCHA Key. - reCAPTCHA Enterprise leverages platform-specific - checks like Apple App Attest and Apple - DeviceCheck to protect your app from abuse. - Providing these fields allows reCAPTCHA - Enterprise to get a better assessment of the - integrity of your app. + reCAPTCHA leverages platform-specific checks + like Apple App Attest and Apple DeviceCheck to + protect your app from abuse. Providing these + fields allows reCAPTCHA to get a better + assessment of the integrity of your app. """ allow_all_bundle_ids: bool = proto.Field( @@ -2644,30 +2646,28 @@ class FirewallAction(proto.Message): This field is a member of `oneof`_ ``firewall_action_oneof``. block (google.cloud.recaptchaenterprise_v1.types.FirewallAction.BlockAction): - This action will deny access to a given page. - The user will get an HTTP error code. + This action denies access to a given page. + The user gets an HTTP error code. This field is a member of `oneof`_ ``firewall_action_oneof``. include_recaptcha_script (google.cloud.recaptchaenterprise_v1.types.FirewallAction.IncludeRecaptchaScriptAction): - This action will inject reCAPTCHA JavaScript - code into the HTML page returned by the site - backend. + This action injects reCAPTCHA JavaScript code + into the HTML page returned by the site backend. This field is a member of `oneof`_ ``firewall_action_oneof``. redirect (google.cloud.recaptchaenterprise_v1.types.FirewallAction.RedirectAction): - This action will redirect the request to a - ReCaptcha interstitial to attach a token. + This action redirects the request to a + reCAPTCHA interstitial to attach a token. This field is a member of `oneof`_ ``firewall_action_oneof``. substitute (google.cloud.recaptchaenterprise_v1.types.FirewallAction.SubstituteAction): - This action will transparently serve a - different page to an offending user. + This action transparently serves a different + page to an offending user. This field is a member of `oneof`_ ``firewall_action_oneof``. set_header (google.cloud.recaptchaenterprise_v1.types.FirewallAction.SetHeaderAction): - This action will set a custom header but - allow the request to continue to the customer - backend. + This action sets a custom header but allow + the request to continue to the customer backend. This field is a member of `oneof`_ ``firewall_action_oneof``. """ @@ -2693,7 +2693,7 @@ class IncludeRecaptchaScriptAction(proto.Message): class RedirectAction(proto.Message): r"""A redirect action returns a 307 (temporary redirect) - response, pointing the user to a ReCaptcha interstitial page to + response, pointing the user to a reCAPTCHA interstitial page to attach a token. """ @@ -3089,6 +3089,91 @@ class AddIpOverrideResponse(proto.Message): r"""Response for AddIpOverride.""" +class RemoveIpOverrideRequest(proto.Message): + r"""The removeIpOverride request message. + + Attributes: + name (str): + Required. The name of the key from which the IP override is + removed, in the format ``projects/{project}/keys/{key}``. + ip_override_data (google.cloud.recaptchaenterprise_v1.types.IpOverrideData): + Required. IP override to be removed from the + key. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ip_override_data: "IpOverrideData" = proto.Field( + proto.MESSAGE, + number=2, + message="IpOverrideData", + ) + + +class RemoveIpOverrideResponse(proto.Message): + r"""Response for RemoveIpOverride.""" + + +class ListIpOverridesRequest(proto.Message): + r"""The ListIpOverrides request message. + + Attributes: + parent (str): + Required. The parent key for which the IP overrides are + listed, in the format ``projects/{project}/keys/{key}``. + page_size (int): + Optional. The maximum number of overrides to return. Default + is 10. Max limit is 100. If the number of overrides is less + than the page_size, all overrides are returned. If the page + size is more than 100, it is coerced to 100. + page_token (str): + Optional. The next_page_token value returned from a previous + ListIpOverridesRequest, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListIpOverridesResponse(proto.Message): + r"""Response for ListIpOverrides. + + Attributes: + ip_overrides (MutableSequence[google.cloud.recaptchaenterprise_v1.types.IpOverrideData]): + IP Overrides details. + next_page_token (str): + Token to retrieve the next page of results. + If this field is empty, no keys remain in the + results. + """ + + @property + def raw_page(self): + return self + + ip_overrides: MutableSequence["IpOverrideData"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="IpOverrideData", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + class RelatedAccountGroupMembership(proto.Message): r"""A membership in a group of related accounts. @@ -3179,7 +3264,7 @@ class WafFeature(proto.Enum): EXPRESS = 5 class WafService(proto.Enum): - r"""Web Application Firewalls supported by reCAPTCHA Enterprise. + r"""Web Application Firewalls supported by reCAPTCHA. Values: WAF_SERVICE_UNSPECIFIED (0): @@ -3190,11 +3275,14 @@ class WafService(proto.Enum): Fastly CLOUDFLARE (4): Cloudflare + AKAMAI (5): + Akamai """ WAF_SERVICE_UNSPECIFIED = 0 CA = 1 FASTLY = 3 CLOUDFLARE = 4 + AKAMAI = 5 waf_service: WafService = proto.Field( proto.ENUM, diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_async.py b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_async.py new file mode 100644 index 000000000000..a12de57ccb10 --- /dev/null +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListIpOverrides +# 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-recaptcha-enterprise + + +# [START recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_ListIpOverrides_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recaptchaenterprise_v1 + + +async def sample_list_ip_overrides(): + # Create a client + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceAsyncClient() + + # Initialize request argument(s) + request = recaptchaenterprise_v1.ListIpOverridesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ip_overrides(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_ListIpOverrides_async] diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_sync.py b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_sync.py new file mode 100644 index 000000000000..b1daef7ff847 --- /dev/null +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 ListIpOverrides +# 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-recaptcha-enterprise + + +# [START recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_ListIpOverrides_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 recaptchaenterprise_v1 + + +def sample_list_ip_overrides(): + # Create a client + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Initialize request argument(s) + request = recaptchaenterprise_v1.ListIpOverridesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ip_overrides(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_ListIpOverrides_sync] diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_async.py b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_async.py new file mode 100644 index 000000000000..0afc90fd3a36 --- /dev/null +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 RemoveIpOverride +# 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-recaptcha-enterprise + + +# [START recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_RemoveIpOverride_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recaptchaenterprise_v1 + + +async def sample_remove_ip_override(): + # Create a client + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceAsyncClient() + + # Initialize request argument(s) + ip_override_data = recaptchaenterprise_v1.IpOverrideData() + ip_override_data.ip = "ip_value" + ip_override_data.override_type = "ALLOW" + + request = recaptchaenterprise_v1.RemoveIpOverrideRequest( + name="name_value", + ip_override_data=ip_override_data, + ) + + # Make the request + response = await client.remove_ip_override(request=request) + + # Handle the response + print(response) + +# [END recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_RemoveIpOverride_async] diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_sync.py b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_sync.py new file mode 100644 index 000000000000..da8d58b09bd8 --- /dev/null +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 RemoveIpOverride +# 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-recaptcha-enterprise + + +# [START recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_RemoveIpOverride_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 recaptchaenterprise_v1 + + +def sample_remove_ip_override(): + # Create a client + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Initialize request argument(s) + ip_override_data = recaptchaenterprise_v1.IpOverrideData() + ip_override_data.ip = "ip_value" + ip_override_data.override_type = "ALLOW" + + request = recaptchaenterprise_v1.RemoveIpOverrideRequest( + name="name_value", + ip_override_data=ip_override_data, + ) + + # Make the request + response = client.remove_ip_override(request=request) + + # Handle the response + print(response) + +# [END recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_RemoveIpOverride_sync] diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/snippet_metadata_google.cloud.recaptchaenterprise.v1.json b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/snippet_metadata_google.cloud.recaptchaenterprise.v1.json index 1702e3084776..4093ef51329b 100644 --- a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/snippet_metadata_google.cloud.recaptchaenterprise.v1.json +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/snippet_metadata_google.cloud.recaptchaenterprise.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-recaptcha-enterprise", - "version": "1.23.0" + "version": "1.24.0" }, "snippets": [ { @@ -1810,6 +1810,167 @@ ], "title": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_firewall_policies_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recaptchaenterprise_v1.RecaptchaEnterpriseServiceAsyncClient", + "shortName": "RecaptchaEnterpriseServiceAsyncClient" + }, + "fullName": "google.cloud.recaptchaenterprise_v1.RecaptchaEnterpriseServiceAsyncClient.list_ip_overrides", + "method": { + "fullName": "google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService.ListIpOverrides", + "service": { + "fullName": "google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService", + "shortName": "RecaptchaEnterpriseService" + }, + "shortName": "ListIpOverrides" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recaptchaenterprise_v1.types.ListIpOverridesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.pagers.ListIpOverridesAsyncPager", + "shortName": "list_ip_overrides" + }, + "description": "Sample for ListIpOverrides", + "file": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_ListIpOverrides_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient", + "shortName": "RecaptchaEnterpriseServiceClient" + }, + "fullName": "google.cloud.recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient.list_ip_overrides", + "method": { + "fullName": "google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService.ListIpOverrides", + "service": { + "fullName": "google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService", + "shortName": "RecaptchaEnterpriseService" + }, + "shortName": "ListIpOverrides" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recaptchaenterprise_v1.types.ListIpOverridesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.pagers.ListIpOverridesPager", + "shortName": "list_ip_overrides" + }, + "description": "Sample for ListIpOverrides", + "file": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_ListIpOverrides_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": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_list_ip_overrides_sync.py" + }, { "canonical": true, "clientMethod": { @@ -2446,6 +2607,175 @@ ], "title": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_migrate_key_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recaptchaenterprise_v1.RecaptchaEnterpriseServiceAsyncClient", + "shortName": "RecaptchaEnterpriseServiceAsyncClient" + }, + "fullName": "google.cloud.recaptchaenterprise_v1.RecaptchaEnterpriseServiceAsyncClient.remove_ip_override", + "method": { + "fullName": "google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService.RemoveIpOverride", + "service": { + "fullName": "google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService", + "shortName": "RecaptchaEnterpriseService" + }, + "shortName": "RemoveIpOverride" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recaptchaenterprise_v1.types.RemoveIpOverrideRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "ip_override_data", + "type": "google.cloud.recaptchaenterprise_v1.types.IpOverrideData" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recaptchaenterprise_v1.types.RemoveIpOverrideResponse", + "shortName": "remove_ip_override" + }, + "description": "Sample for RemoveIpOverride", + "file": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_RemoveIpOverride_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient", + "shortName": "RecaptchaEnterpriseServiceClient" + }, + "fullName": "google.cloud.recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient.remove_ip_override", + "method": { + "fullName": "google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService.RemoveIpOverride", + "service": { + "fullName": "google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseService", + "shortName": "RecaptchaEnterpriseService" + }, + "shortName": "RemoveIpOverride" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recaptchaenterprise_v1.types.RemoveIpOverrideRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "ip_override_data", + "type": "google.cloud.recaptchaenterprise_v1.types.IpOverrideData" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recaptchaenterprise_v1.types.RemoveIpOverrideResponse", + "shortName": "remove_ip_override" + }, + "description": "Sample for RemoveIpOverride", + "file": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_RemoveIpOverride_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recaptchaenterprise_v1_generated_recaptcha_enterprise_service_remove_ip_override_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-recaptcha-enterprise/scripts/fixup_recaptchaenterprise_v1_keywords.py b/packages/google-cloud-recaptcha-enterprise/scripts/fixup_recaptchaenterprise_v1_keywords.py index 36e16174f78a..f3a45648c28e 100644 --- a/packages/google-cloud-recaptcha-enterprise/scripts/fixup_recaptchaenterprise_v1_keywords.py +++ b/packages/google-cloud-recaptcha-enterprise/scripts/fixup_recaptchaenterprise_v1_keywords.py @@ -50,10 +50,12 @@ class recaptchaenterpriseCallTransformer(cst.CSTTransformer): 'get_key': ('name', ), 'get_metrics': ('name', ), 'list_firewall_policies': ('parent', 'page_size', 'page_token', ), + 'list_ip_overrides': ('parent', 'page_size', 'page_token', ), 'list_keys': ('parent', 'page_size', 'page_token', ), 'list_related_account_group_memberships': ('parent', 'page_size', 'page_token', ), 'list_related_account_groups': ('parent', 'page_size', 'page_token', ), 'migrate_key': ('name', 'skip_billing_check', ), + 'remove_ip_override': ('name', 'ip_override_data', ), 'reorder_firewall_policies': ('parent', 'names', ), 'retrieve_legacy_secret_key': ('key', ), 'search_related_account_group_memberships': ('project', 'account_id', 'hashed_account_id', 'page_size', 'page_token', ), diff --git a/packages/google-cloud-recaptcha-enterprise/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py b/packages/google-cloud-recaptcha-enterprise/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py index cab29893173f..7bcde7cb5cf5 100644 --- a/packages/google-cloud-recaptcha-enterprise/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py +++ b/packages/google-cloud-recaptcha-enterprise/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py @@ -4609,6 +4609,896 @@ async def test_add_ip_override_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + recaptchaenterprise.RemoveIpOverrideRequest, + dict, + ], +) +def test_remove_ip_override(request_type, transport: str = "grpc"): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.RemoveIpOverrideResponse() + response = client.remove_ip_override(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = recaptchaenterprise.RemoveIpOverrideRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, recaptchaenterprise.RemoveIpOverrideResponse) + + +def test_remove_ip_override_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = recaptchaenterprise.RemoveIpOverrideRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.remove_ip_override(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == recaptchaenterprise.RemoveIpOverrideRequest( + name="name_value", + ) + + +def test_remove_ip_override_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 = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.remove_ip_override 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_ip_override + ] = mock_rpc + request = {} + client.remove_ip_override(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.remove_ip_override(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_remove_ip_override_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.remove_ip_override + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.remove_ip_override + ] = mock_rpc + + request = {} + await client.remove_ip_override(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.remove_ip_override(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_remove_ip_override_async( + transport: str = "grpc_asyncio", + request_type=recaptchaenterprise.RemoveIpOverrideRequest, +): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.RemoveIpOverrideResponse() + ) + response = await client.remove_ip_override(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = recaptchaenterprise.RemoveIpOverrideRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, recaptchaenterprise.RemoveIpOverrideResponse) + + +@pytest.mark.asyncio +async def test_remove_ip_override_async_from_dict(): + await test_remove_ip_override_async(request_type=dict) + + +def test_remove_ip_override_field_headers(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.RemoveIpOverrideRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + call.return_value = recaptchaenterprise.RemoveIpOverrideResponse() + client.remove_ip_override(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_remove_ip_override_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.RemoveIpOverrideRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.RemoveIpOverrideResponse() + ) + await client.remove_ip_override(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_remove_ip_override_flattened(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.RemoveIpOverrideResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_ip_override( + name="name_value", + ip_override_data=recaptchaenterprise.IpOverrideData(ip="ip_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ip_override_data + mock_val = recaptchaenterprise.IpOverrideData(ip="ip_value") + assert arg == mock_val + + +def test_remove_ip_override_flattened_error(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_ip_override( + recaptchaenterprise.RemoveIpOverrideRequest(), + name="name_value", + ip_override_data=recaptchaenterprise.IpOverrideData(ip="ip_value"), + ) + + +@pytest.mark.asyncio +async def test_remove_ip_override_flattened_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.RemoveIpOverrideResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.RemoveIpOverrideResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_ip_override( + name="name_value", + ip_override_data=recaptchaenterprise.IpOverrideData(ip="ip_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ip_override_data + mock_val = recaptchaenterprise.IpOverrideData(ip="ip_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_remove_ip_override_flattened_error_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_ip_override( + recaptchaenterprise.RemoveIpOverrideRequest(), + name="name_value", + ip_override_data=recaptchaenterprise.IpOverrideData(ip="ip_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + recaptchaenterprise.ListIpOverridesRequest, + dict, + ], +) +def test_list_ip_overrides(request_type, transport: str = "grpc"): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.ListIpOverridesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_ip_overrides(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = recaptchaenterprise.ListIpOverridesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIpOverridesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_ip_overrides_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = recaptchaenterprise.ListIpOverridesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_ip_overrides(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == recaptchaenterprise.ListIpOverridesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_ip_overrides_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 = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_ip_overrides 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_ip_overrides + ] = mock_rpc + request = {} + client.list_ip_overrides(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_ip_overrides(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_ip_overrides_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_ip_overrides + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_ip_overrides + ] = mock_rpc + + request = {} + await client.list_ip_overrides(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_ip_overrides(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_ip_overrides_async( + transport: str = "grpc_asyncio", + request_type=recaptchaenterprise.ListIpOverridesRequest, +): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListIpOverridesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_ip_overrides(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = recaptchaenterprise.ListIpOverridesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIpOverridesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_ip_overrides_async_from_dict(): + await test_list_ip_overrides_async(request_type=dict) + + +def test_list_ip_overrides_field_headers(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.ListIpOverridesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + call.return_value = recaptchaenterprise.ListIpOverridesResponse() + client.list_ip_overrides(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_ip_overrides_field_headers_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recaptchaenterprise.ListIpOverridesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListIpOverridesResponse() + ) + await client.list_ip_overrides(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_ip_overrides_flattened(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.ListIpOverridesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_ip_overrides( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_ip_overrides_flattened_error(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_ip_overrides( + recaptchaenterprise.ListIpOverridesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_ip_overrides_flattened_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = recaptchaenterprise.ListIpOverridesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListIpOverridesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_ip_overrides( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_ip_overrides_flattened_error_async(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_ip_overrides( + recaptchaenterprise.ListIpOverridesRequest(), + parent="parent_value", + ) + + +def test_list_ip_overrides_pager(transport_name: str = "grpc"): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + ], + next_page_token="abc", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[], + next_page_token="def", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + ], + next_page_token="ghi", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_ip_overrides(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, recaptchaenterprise.IpOverrideData) for i in results) + + +def test_list_ip_overrides_pages(transport_name: str = "grpc"): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + ], + next_page_token="abc", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[], + next_page_token="def", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + ], + next_page_token="ghi", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + ], + ), + RuntimeError, + ) + pages = list(client.list_ip_overrides(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_ip_overrides_async_pager(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + ], + next_page_token="abc", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[], + next_page_token="def", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + ], + next_page_token="ghi", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_ip_overrides( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, recaptchaenterprise.IpOverrideData) for i in responses) + + +@pytest.mark.asyncio +async def test_list_ip_overrides_async_pages(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + ], + next_page_token="abc", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[], + next_page_token="def", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + ], + next_page_token="ghi", + ), + recaptchaenterprise.ListIpOverridesResponse( + ip_overrides=[ + recaptchaenterprise.IpOverrideData(), + recaptchaenterprise.IpOverrideData(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_ip_overrides(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + @pytest.mark.parametrize( "request_type", [ @@ -9253,6 +10143,52 @@ def test_add_ip_override_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_ip_override_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + call.return_value = recaptchaenterprise.RemoveIpOverrideResponse() + client.remove_ip_override(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.RemoveIpOverrideRequest() + + 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_ip_overrides_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + call.return_value = recaptchaenterprise.ListIpOverridesResponse() + client.list_ip_overrides(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListIpOverridesRequest() + + 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_metrics_empty_call_grpc(): @@ -9771,6 +10707,62 @@ async def test_add_ip_override_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_ip_override_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_ip_override), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.RemoveIpOverrideResponse() + ) + await client.remove_ip_override(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.RemoveIpOverrideRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_ip_overrides_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_ip_overrides), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListIpOverridesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_ip_overrides(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListIpOverridesRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -10105,6 +11097,8 @@ def test_recaptcha_enterprise_service_base_transport(): "delete_key", "migrate_key", "add_ip_override", + "remove_ip_override", + "list_ip_overrides", "get_metrics", "create_firewall_policy", "list_firewall_policies", diff --git a/packages/google-cloud-securitycentermanagement/CHANGELOG.md b/packages/google-cloud-securitycentermanagement/CHANGELOG.md index 3573358f8b28..aee2513491eb 100644 --- a/packages/google-cloud-securitycentermanagement/CHANGELOG.md +++ b/packages/google-cloud-securitycentermanagement/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.16](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securitycentermanagement-v0.1.15...google-cloud-securitycentermanagement-v0.1.16) (2024-10-31) + + +### Documentation + +* update documentation ([f611927](https://github.com/googleapis/google-cloud-python/commit/f61192719e42218a751e30ad9aca4c40d795c63a)) + ## [0.1.15](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securitycentermanagement-v0.1.14...google-cloud-securitycentermanagement-v0.1.15) (2024-10-24) diff --git a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement/gapic_version.py b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement/gapic_version.py index 564cdfade642..5879ee6ab325 100644 --- a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement/gapic_version.py +++ b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.15" # {x-release-please-version} +__version__ = "0.1.16" # {x-release-please-version} diff --git a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/gapic_version.py b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/gapic_version.py index 564cdfade642..5879ee6ab325 100644 --- a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/gapic_version.py +++ b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.15" # {x-release-please-version} +__version__ = "0.1.16" # {x-release-please-version} diff --git a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/async_client.py b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/async_client.py index bee3e71bff68..3028722cbfd5 100644 --- a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/async_client.py +++ b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/async_client.py @@ -316,10 +316,11 @@ async def list_effective_security_health_analytics_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: r"""Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors (no descendants). + [EffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.EffectiveSecurityHealthAnalyticsCustomModule] + resources for the given parent. This includes resident modules + defined at the scope of the parent, and inherited modules, + inherited from ancestor organizations, folders, and projects (no + descendants). .. code-block:: python @@ -350,16 +351,15 @@ async def sample_list_effective_security_health_analytics_custom_modules(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing effective - Security Health Analytics custom - modules. + The request object. Request message for + [SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules]. parent (:class:`str`): Required. Name of parent to list effective custom - modules. specified in one of the following formats: + modules, in one of the following formats: - ``organizations/{organization}/locations/{location}`` - - ``folders/{folder}/locations/{location}`` or - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -372,13 +372,11 @@ async def sample_list_effective_security_health_analytics_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing - effective Security Health Analytics - custom modules. + Response message for + [SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules]. - Iterating over this object will yield - results and resolve additional pages - automatically. + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -458,7 +456,7 @@ async def get_effective_security_health_analytics_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.EffectiveSecurityHealthAnalyticsCustomModule: r"""Gets details of a single - EffectiveSecurityHealthAnalyticsCustomModule. + [EffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.EffectiveSecurityHealthAnalyticsCustomModule]. .. code-block:: python @@ -488,15 +486,15 @@ async def sample_get_effective_security_health_analytics_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Message for getting a - EffectiveSecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEffectiveSecurityHealthAnalyticsCustomModule]. name (:class:`str`): Required. The full resource name of the custom module, specified in one of the following formats: - - ``organizations/organization/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` - - ``folders/folder/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` - - ``projects/project/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` + - ``organizations/organization/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` + - ``folders/folder/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` + - ``projects/project/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -509,20 +507,16 @@ async def sample_get_effective_security_health_analytics_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the representation of - a Security Health Analytics custom module at a + The representation of a Security Health Analytics custom module at a specified level of the resource hierarchy: organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablementState property in - EffectiveSecurityHealthAnalyticsCustomModule is set - to the value that is effective in the parent, instead - of INHERITED. For example, if the module is enabled - in a parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. + is inherited from an ancestor organization or folder, + then the enablement state is set to the value that is + effective in the parent, not to INHERITED. For + example, if the module is enabled in an organization + or folder, then the effective enablement state for + the module is ENABLED in all descendant folders or + projects. """ # Create or coerce a protobuf request object. @@ -591,10 +585,11 @@ async def list_security_health_analytics_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager: r"""Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors (no descendants). + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + resources for the given parent. This includes resident modules + defined at the scope of the parent, and inherited modules, + inherited from ancestor organizations, folders, and projects (no + descendants). .. code-block:: python @@ -625,12 +620,12 @@ async def sample_list_security_health_analytics_custom_modules(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing Security - Health Analytics custom modules. + The request object. Request message for + [SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules]. parent (:class:`str`): - Required. Name of parent organization, folder, or - project in which to list custom modules, specified in - one of the following formats: + Required. Name of the parent organization, folder, or + project in which to list custom modules, in one of the + following formats: - ``organizations/{organization}/locations/{location}`` - ``folders/{folder}/locations/{location}`` @@ -647,11 +642,11 @@ async def sample_list_security_health_analytics_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing Security - Health Analytics custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. + Response message for + [SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules]. + + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -731,8 +726,9 @@ async def list_descendant_security_health_analytics_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: r"""Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent's CRM descendants. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + resources under the given organization, folder, or project and + all of its descendants. .. code-block:: python @@ -763,13 +759,12 @@ async def sample_list_descendant_security_health_analytics_custom_modules(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]]): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. + The request object. Request message for + [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. parent (:class:`str`): Required. Name of the parent organization, folder, or - project in which to list custom modules, specified in - one of the following formats: + project in which to list custom modules, in one of the + following formats: - ``organizations/{organization}/locations/{location}`` - ``folders/{folder}/locations/{location}`` @@ -786,13 +781,11 @@ async def sample_list_descendant_security_health_analytics_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: - Response message for listing - descendant Security Health Analytics - custom modules. + Response message for + [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. - Iterating over this object will yield - results and resolve additional pages - automatically. + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -871,7 +864,8 @@ async def get_security_health_analytics_custom_module( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.SecurityHealthAnalyticsCustomModule: - r"""Retrieves a SecurityHealthAnalyticsCustomModule. + r"""Retrieves a + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule]. .. code-block:: python @@ -901,10 +895,12 @@ async def sample_get_security_health_analytics_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Message for getting a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.GetSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetSecurityHealthAnalyticsCustomModule]. name (:class:`str`): - Required. Name of the resource + Required. Name of the resource, in the format + ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}``. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -924,7 +920,7 @@ async def sample_get_security_health_analytics_custom_module(): the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -997,11 +993,11 @@ async def create_security_health_analytics_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.SecurityHealthAnalyticsCustomModule: r"""Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + at the scope of the given organization, folder, or project, and + also creates inherited ``SecurityHealthAnalyticsCustomModule`` + resources for all folders and projects that are descendants of + the given parent. These modules are enabled by default. .. code-block:: python @@ -1031,12 +1027,11 @@ async def sample_create_security_health_analytics_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Message for creating a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.CreateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.CreateSecurityHealthAnalyticsCustomModule]. parent (:class:`str`): Required. Name of the parent organization, folder, or - project of the module, specified in one of the following - formats: + project of the module, in one of the following formats: - ``organizations/{organization}/locations/{location}`` - ``folders/{folder}/locations/{location}`` @@ -1046,7 +1041,7 @@ async def sample_create_security_health_analytics_custom_module(): on the ``request`` instance; if ``request`` is provided, this should not be set. security_health_analytics_custom_module (:class:`google.cloud.securitycentermanagement_v1.types.SecurityHealthAnalyticsCustomModule`): - Required. The resource being created + Required. The resource being created. This corresponds to the ``security_health_analytics_custom_module`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1066,7 +1061,7 @@ async def sample_create_security_health_analytics_custom_module(): the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -1142,13 +1137,13 @@ async def update_security_health_analytics_custom_module( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.SecurityHealthAnalyticsCustomModule: - r"""Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. + r"""Updates the + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + under the given name based on the given update mask. Updating + the enablement state is supported on both resident and inherited + modules (though resident modules cannot have an enablement state + of "inherited"). Updating the display name and custom + configuration of a module is supported on resident modules only. .. code-block:: python @@ -1177,19 +1172,22 @@ async def sample_update_security_health_analytics_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Message for updating a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.UpdateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.UpdateSecurityHealthAnalyticsCustomModule]. security_health_analytics_custom_module (:class:`google.cloud.securitycentermanagement_v1.types.SecurityHealthAnalyticsCustomModule`): - Required. The resource being updated + Required. The resource being updated. This corresponds to the ``security_health_analytics_custom_module`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. The only - fields that can be updated are ``enablement_state`` and - ``custom_config``. If empty or set to the wildcard value - ``*``, both ``enablement_state`` and ``custom_config`` - are updated. + Required. The fields to update. The following values are + valid: + + - ``custom_config`` + - ``enablement_state`` + + If you omit this field or set it to the wildcard value + ``*``, then all eligible fields are updated. This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this @@ -1210,7 +1208,7 @@ async def sample_update_security_health_analytics_custom_module(): the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -1293,9 +1291,9 @@ async def delete_security_health_analytics_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + and all of its descendants in the resource hierarchy. This + method is only supported for resident custom modules. .. code-block:: python @@ -1322,16 +1320,15 @@ async def sample_delete_security_health_analytics_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Message for deleting a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.DeleteSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.DeleteSecurityHealthAnalyticsCustomModule]. name (:class:`str`): - Required. The resource name of the SHA custom module. - - Its format is: + Required. The resource name of the SHA custom module, in + one of the following formats: - - ``organizations/{organization}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. - - ``folders/{folder}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. - - ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. + - ``organizations/{organization}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1408,8 +1405,9 @@ async def simulate_security_health_analytics_custom_module( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.SimulateSecurityHealthAnalyticsCustomModuleResponse: - r"""Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. + r"""Simulates the result of using a + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + to check a resource. .. code-block:: python @@ -1443,16 +1441,15 @@ async def sample_simulate_security_health_analytics_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]]): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. + The request object. Request message for + [SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule]. + The maximum size of the request is 4 MiB. parent (:class:`str`): Required. The relative resource name of the organization, project, or folder. For more information - about relative resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}``. + about relative resource names, see `AIP-122: Resource + names `__. Example: + ``organizations/{organization_id}``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1479,8 +1476,8 @@ async def sample_simulate_security_health_analytics_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a SecurityHealthAnalyticsCustomModule - against a given resource. + Response message for + [SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule]. """ # Create or coerce a protobuf request object. @@ -1586,14 +1583,15 @@ async def sample_list_effective_event_threat_detection_custom_modules(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request message for listing effective - Event Threat Detection custom modules. + The request object. Request message for + [SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules]. parent (:class:`str`): Required. Name of parent to list effective custom - modules. Its format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + modules, in one of the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1606,13 +1604,11 @@ async def sample_list_effective_event_threat_detection_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListEffectiveEventThreatDetectionCustomModulesAsyncPager: - Response message for listing - effective Event Threat Detection custom - modules. + Response message for + [SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules]. - Iterating over this object will yield - results and resolve additional pages - automatically. + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -1691,14 +1687,20 @@ async def get_effective_event_threat_detection_custom_module( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.EffectiveEventThreatDetectionCustomModule: - r"""Gets an effective ETD custom module. Retrieves the effective - module at the given level. The difference between an - EffectiveCustomModule and a CustomModule is that the fields for - an EffectiveCustomModule are computed from ancestors if needed. - For example, the enablement_state for a CustomModule can be - either ENABLED, DISABLED, or INHERITED. Where as the - enablement_state for an EffectiveCustomModule is always computed - to ENABLED or DISABLED (the effective enablement_state). + r"""Gets the effective Event Threat Detection custom module at the + given level. + + The difference between an + [EffectiveEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EffectiveEventThreatDetectionCustomModule] + and an + [EventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule] + is that the fields for an + ``EffectiveEventThreatDetectionCustomModule`` are computed from + ancestors if needed. For example, the enablement state for an + ``EventThreatDetectionCustomModule`` can be ``ENABLED``, + ``DISABLED``, or ``INHERITED``. In contrast, the enablement + state for an ``EffectiveEventThreatDetectionCustomModule`` is + always computed as ``ENABLED`` or ``DISABLED``. .. code-block:: python @@ -1728,16 +1730,16 @@ async def sample_get_effective_event_threat_detection_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Message for getting a - EffectiveEventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEffectiveEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEffectiveEventThreatDetectionCustomModule]. name (:class:`str`): - Required. The resource name of the ETD custom module. - - Its format is: + Required. The resource name of the Event Threat + Detection custom module, in one of the following + formats: - - ``organizations/{organization}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1750,17 +1752,16 @@ async def sample_get_effective_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the representation of - EventThreatDetectionCustomModule at a given level - taking hierarchy into account and resolving various - fields accordingly. e.g. if the module is enabled at - the ancestor level, effective modules at all - descendant levels will have enablement_state set to - ENABLED. Similarly, if module.inherited is set, then - effective module's config will contain the ancestor's - config details. - EffectiveEventThreatDetectionCustomModule is - read-only. + The representation of an + [EventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule] + at a given level, taking hierarchy into account and + resolving various fields accordingly. For example, if + the module is enabled at the ancestor level, then + effective modules at all descendant levels will have + their enablement state set to ENABLED. Similarly, if + module.inherited is set, then the effective module's + configuration will reflect the ancestor's + configuration. """ # Create or coerce a protobuf request object. @@ -1829,9 +1830,9 @@ async def list_event_threat_detection_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEventThreatDetectionCustomModulesAsyncPager: r"""Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. + the given organization, folder, or project. This + includes resident modules defined at the scope of the + parent along with modules inherited from ancestors. .. code-block:: python @@ -1862,14 +1863,15 @@ async def sample_list_event_threat_detection_custom_modules(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request message for listing Event - Threat Detection custom modules. + The request object. Request message for + [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules]. parent (:class:`str`): - Required. Name of parent to list custom modules. Its - format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent to list custom modules, in one + of the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1882,11 +1884,11 @@ async def sample_list_event_threat_detection_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListEventThreatDetectionCustomModulesAsyncPager: - Response message for listing Event - Threat Detection custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. + Response message for + [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules]. + + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -1968,8 +1970,8 @@ async def list_descendant_event_threat_detection_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager: r"""Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. + modules for the given organization, folder, or project + and its descendants. .. code-block:: python @@ -2000,15 +2002,15 @@ async def sample_list_descendant_event_threat_detection_custom_modules(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]]): - The request object. Request message for listing - descendant Event Threat Detection custom - modules. + The request object. Request message for + [SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules]. parent (:class:`str`): - Required. Name of parent to list custom modules. Its - format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent to list custom modules, in one + of the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -2021,13 +2023,11 @@ async def sample_list_descendant_event_threat_detection_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListDescendantEventThreatDetectionCustomModulesAsyncPager: - Response message for listing - descendant Event Threat Detection custom - modules. + Response message for + [SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules]. - Iterating over this object will yield - results and resolve additional pages - automatically. + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -2136,16 +2136,16 @@ async def sample_get_event_threat_detection_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Message for getting a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEventThreatDetectionCustomModule]. name (:class:`str`): - Required. The resource name of the ETD custom module. - - Its format is: + Required. The resource name of the Event Threat + Detection custom module, in one of the following + formats: - - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2158,12 +2158,12 @@ async def sample_get_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ # Create or coerce a protobuf request object. @@ -2237,9 +2237,9 @@ async def create_event_threat_detection_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.EventThreatDetectionCustomModule: r"""Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are + module at the scope of the given organization, folder, + or project, and creates inherited custom modules for all + descendants of the given parent. These modules are enabled by default. .. code-block:: python @@ -2270,21 +2270,24 @@ async def sample_create_event_threat_detection_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Message for creating a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.CreateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.CreateEventThreatDetectionCustomModule]. parent (:class:`str`): - Required. Name of parent for the module. Its format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent for the module, in one of the + following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. event_threat_detection_custom_module (:class:`google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule`): Required. The module to create. The - event_threat_detection_custom_module.name will be - ignored and server generated. + [EventThreatDetectionCustomModule.name][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule.name] + field is ignored; Security Command Center generates the + name. This corresponds to the ``event_threat_detection_custom_module`` field on the ``request`` instance; if ``request`` is provided, this @@ -2297,12 +2300,12 @@ async def sample_create_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ # Create or coerce a protobuf request object. @@ -2416,18 +2419,13 @@ async def sample_update_event_threat_detection_custom_module(): The request object. Message for updating a EventThreatDetectionCustomModule event_threat_detection_custom_module (:class:`google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule`): - Required. The module being updated + Required. The module being updated. This corresponds to the ``event_threat_detection_custom_module`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Field mask is used to specify the fields to be - overwritten in the EventThreatDetectionCustomModule - resource by the update. The fields specified in the - update_mask are relative to the resource, not the full - request. A field will be overwritten if it is in the - mask. If the user does not provide a mask then all - fields will be overwritten. + Required. The fields to update. If + omitted, then all fields are updated. This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this @@ -2440,12 +2438,12 @@ async def sample_update_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ # Create or coerce a protobuf request object. @@ -2525,9 +2523,9 @@ async def delete_event_threat_detection_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. + module and all of its descendants in the resource + hierarchy. This method is only supported for resident + custom modules. .. code-block:: python @@ -2554,16 +2552,16 @@ async def sample_delete_event_threat_detection_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Message for deleting a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.DeleteEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.DeleteEventThreatDetectionCustomModule]. name (:class:`str`): - Required. The resource name of the ETD custom module. - - Its format is: + Required. The resource name of the Event Threat + Detection custom module, in one of the following + formats: - - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2668,8 +2666,8 @@ async def sample_validate_event_threat_detection_custom_module(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]]): - The request object. Request to validate an Event Threat - Detection custom module. + The request object. Request message for + [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule]. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2678,8 +2676,8 @@ async def sample_validate_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. + Response message for + [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule]. """ # Create or coerce a protobuf request object. @@ -2761,25 +2759,23 @@ async def sample_get_security_center_service(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.GetSecurityCenterServiceRequest, dict]]): - The request object. Request message for getting a - Security Command Center service. + The request object. Request message for + [SecurityCenterManagement.GetSecurityCenterService][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetSecurityCenterService]. name (:class:`str`): Required. The Security Command Center service to - retrieve. - - Formats: + retrieve, in one of the following formats: - organizations/{organization}/locations/{location}/securityCenterServices/{service} - folders/{folder}/locations/{location}/securityCenterServices/{service} - projects/{project}/locations/{location}/securityCenterServices/{service} - The possible values for id {service} are: + The following values are valid for ``{service}``: - - container-threat-detection - - event-threat-detection - - security-health-analytics - - vm-threat-detection - - web-security-scanner + - ``container-threat-detection`` + - ``event-threat-detection`` + - ``security-health-analytics`` + - ``vm-threat-detection`` + - ``web-security-scanner`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2800,8 +2796,8 @@ async def sample_get_security_center_service(): configured at the organization, folder, or project level. Service settings at the organization or folder level are - inherited by those in child folders and - projects. + inherited by those in descendant folders + and projects. """ # Create or coerce a protobuf request object. @@ -2897,17 +2893,16 @@ async def sample_list_security_center_services(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.ListSecurityCenterServicesRequest, dict]]): - The request object. Request message for listing Security - Command Center services. + The request object. Request message for + [SecurityCenterManagement.ListSecurityCenterServices][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityCenterServices]. parent (:class:`str`): Required. The name of the parent to list Security - Command Center services. - - Formats: + Command Center services, in one of the following + formats: - - organizations/{organization}/locations/{location} - - folders/{folder}/locations/{location} - - projects/{project}/locations/{location} + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -2920,11 +2915,11 @@ async def sample_list_security_center_services(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListSecurityCenterServicesAsyncPager: - Response message for listing Security - Command Center services. - Iterating over this object will yield - results and resolve additional pages - automatically. + Response message for + [SecurityCenterManagement.ListSecurityCenterServices][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityCenterServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -3032,19 +3027,21 @@ async def sample_update_security_center_service(): Args: request (Optional[Union[google.cloud.securitycentermanagement_v1.types.UpdateSecurityCenterServiceRequest, dict]]): - The request object. Request message for updating a - Security Command Center service. + The request object. Request message for + [SecurityCenterManagement.UpdateSecurityCenterService][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.UpdateSecurityCenterService]. security_center_service (:class:`google.cloud.securitycentermanagement_v1.types.SecurityCenterService`): Required. The updated service. This corresponds to the ``security_center_service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Possible + Required. The fields to update. Accepts the following values: - - "intended_enablement_state" - - "modules" + - ``intended_enablement_state`` + - ``modules`` + + If omitted, then all eligible fields are updated. This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this @@ -3065,8 +3062,8 @@ async def sample_update_security_center_service(): configured at the organization, folder, or project level. Service settings at the organization or folder level are - inherited by those in child folders and - projects. + inherited by those in descendant folders + and projects. """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/client.py b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/client.py index a2e8c1ca6b16..6da9ac36882f 100644 --- a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/client.py +++ b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/client.py @@ -824,10 +824,11 @@ def list_effective_security_health_analytics_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: r"""Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors (no descendants). + [EffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.EffectiveSecurityHealthAnalyticsCustomModule] + resources for the given parent. This includes resident modules + defined at the scope of the parent, and inherited modules, + inherited from ancestor organizations, folders, and projects (no + descendants). .. code-block:: python @@ -858,16 +859,15 @@ def sample_list_effective_security_health_analytics_custom_modules(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing effective - Security Health Analytics custom - modules. + The request object. Request message for + [SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules]. parent (str): Required. Name of parent to list effective custom - modules. specified in one of the following formats: + modules, in one of the following formats: - ``organizations/{organization}/locations/{location}`` - - ``folders/{folder}/locations/{location}`` or - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -880,13 +880,11 @@ def sample_list_effective_security_health_analytics_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListEffectiveSecurityHealthAnalyticsCustomModulesPager: - Response message for listing - effective Security Health Analytics - custom modules. + Response message for + [SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules]. - Iterating over this object will yield - results and resolve additional pages - automatically. + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -965,7 +963,7 @@ def get_effective_security_health_analytics_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.EffectiveSecurityHealthAnalyticsCustomModule: r"""Gets details of a single - EffectiveSecurityHealthAnalyticsCustomModule. + [EffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.EffectiveSecurityHealthAnalyticsCustomModule]. .. code-block:: python @@ -995,15 +993,15 @@ def sample_get_effective_security_health_analytics_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Message for getting a - EffectiveSecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEffectiveSecurityHealthAnalyticsCustomModule]. name (str): Required. The full resource name of the custom module, specified in one of the following formats: - - ``organizations/organization/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` - - ``folders/folder/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` - - ``projects/project/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` + - ``organizations/organization/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` + - ``folders/folder/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` + - ``projects/project/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1016,20 +1014,16 @@ def sample_get_effective_security_health_analytics_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the representation of - a Security Health Analytics custom module at a + The representation of a Security Health Analytics custom module at a specified level of the resource hierarchy: organization, folder, or project. If a custom module - is inherited from a parent organization or folder, - the value of the enablementState property in - EffectiveSecurityHealthAnalyticsCustomModule is set - to the value that is effective in the parent, instead - of INHERITED. For example, if the module is enabled - in a parent organization or folder, the effective - enablement_state for the module in all child folders - or projects is also enabled. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. + is inherited from an ancestor organization or folder, + then the enablement state is set to the value that is + effective in the parent, not to INHERITED. For + example, if the module is enabled in an organization + or folder, then the effective enablement state for + the module is ENABLED in all descendant folders or + projects. """ # Create or coerce a protobuf request object. @@ -1097,10 +1091,11 @@ def list_security_health_analytics_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSecurityHealthAnalyticsCustomModulesPager: r"""Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors (no descendants). + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + resources for the given parent. This includes resident modules + defined at the scope of the parent, and inherited modules, + inherited from ancestor organizations, folders, and projects (no + descendants). .. code-block:: python @@ -1131,12 +1126,12 @@ def sample_list_security_health_analytics_custom_modules(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.ListSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing Security - Health Analytics custom modules. + The request object. Request message for + [SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules]. parent (str): - Required. Name of parent organization, folder, or - project in which to list custom modules, specified in - one of the following formats: + Required. Name of the parent organization, folder, or + project in which to list custom modules, in one of the + following formats: - ``organizations/{organization}/locations/{location}`` - ``folders/{folder}/locations/{location}`` @@ -1153,11 +1148,11 @@ def sample_list_security_health_analytics_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListSecurityHealthAnalyticsCustomModulesPager: - Response message for listing Security - Health Analytics custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. + Response message for + [SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules]. + + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -1236,8 +1231,9 @@ def list_descendant_security_health_analytics_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager: r"""Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent's CRM descendants. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + resources under the given organization, folder, or project and + all of its descendants. .. code-block:: python @@ -1268,13 +1264,12 @@ def sample_list_descendant_security_health_analytics_custom_modules(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.ListDescendantSecurityHealthAnalyticsCustomModulesRequest, dict]): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. + The request object. Request message for + [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. parent (str): Required. Name of the parent organization, folder, or - project in which to list custom modules, specified in - one of the following formats: + project in which to list custom modules, in one of the + following formats: - ``organizations/{organization}/locations/{location}`` - ``folders/{folder}/locations/{location}`` @@ -1291,13 +1286,11 @@ def sample_list_descendant_security_health_analytics_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager: - Response message for listing - descendant Security Health Analytics - custom modules. + Response message for + [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. - Iterating over this object will yield - results and resolve additional pages - automatically. + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -1375,7 +1368,8 @@ def get_security_health_analytics_custom_module( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.SecurityHealthAnalyticsCustomModule: - r"""Retrieves a SecurityHealthAnalyticsCustomModule. + r"""Retrieves a + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule]. .. code-block:: python @@ -1405,10 +1399,12 @@ def sample_get_security_health_analytics_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.GetSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Message for getting a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.GetSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetSecurityHealthAnalyticsCustomModule]. name (str): - Required. Name of the resource + Required. Name of the resource, in the format + ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}``. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1428,7 +1424,7 @@ def sample_get_security_health_analytics_custom_module(): the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -1500,11 +1496,11 @@ def create_security_health_analytics_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.SecurityHealthAnalyticsCustomModule: r"""Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + at the scope of the given organization, folder, or project, and + also creates inherited ``SecurityHealthAnalyticsCustomModule`` + resources for all folders and projects that are descendants of + the given parent. These modules are enabled by default. .. code-block:: python @@ -1534,12 +1530,11 @@ def sample_create_security_health_analytics_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.CreateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Message for creating a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.CreateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.CreateSecurityHealthAnalyticsCustomModule]. parent (str): Required. Name of the parent organization, folder, or - project of the module, specified in one of the following - formats: + project of the module, in one of the following formats: - ``organizations/{organization}/locations/{location}`` - ``folders/{folder}/locations/{location}`` @@ -1549,7 +1544,7 @@ def sample_create_security_health_analytics_custom_module(): on the ``request`` instance; if ``request`` is provided, this should not be set. security_health_analytics_custom_module (google.cloud.securitycentermanagement_v1.types.SecurityHealthAnalyticsCustomModule): - Required. The resource being created + Required. The resource being created. This corresponds to the ``security_health_analytics_custom_module`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1569,7 +1564,7 @@ def sample_create_security_health_analytics_custom_module(): the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -1644,13 +1639,13 @@ def update_security_health_analytics_custom_module( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.SecurityHealthAnalyticsCustomModule: - r"""Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. + r"""Updates the + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + under the given name based on the given update mask. Updating + the enablement state is supported on both resident and inherited + modules (though resident modules cannot have an enablement state + of "inherited"). Updating the display name and custom + configuration of a module is supported on resident modules only. .. code-block:: python @@ -1679,19 +1674,22 @@ def sample_update_security_health_analytics_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.UpdateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Message for updating a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.UpdateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.UpdateSecurityHealthAnalyticsCustomModule]. security_health_analytics_custom_module (google.cloud.securitycentermanagement_v1.types.SecurityHealthAnalyticsCustomModule): - Required. The resource being updated + Required. The resource being updated. This corresponds to the ``security_health_analytics_custom_module`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. The only - fields that can be updated are ``enablement_state`` and - ``custom_config``. If empty or set to the wildcard value - ``*``, both ``enablement_state`` and ``custom_config`` - are updated. + Required. The fields to update. The following values are + valid: + + - ``custom_config`` + - ``enablement_state`` + + If you omit this field or set it to the wildcard value + ``*``, then all eligible fields are updated. This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this @@ -1712,7 +1710,7 @@ def sample_update_security_health_analytics_custom_module(): the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -1794,9 +1792,9 @@ def delete_security_health_analytics_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + and all of its descendants in the resource hierarchy. This + method is only supported for resident custom modules. .. code-block:: python @@ -1823,16 +1821,15 @@ def sample_delete_security_health_analytics_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.DeleteSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Message for deleting a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.DeleteSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.DeleteSecurityHealthAnalyticsCustomModule]. name (str): - Required. The resource name of the SHA custom module. - - Its format is: + Required. The resource name of the SHA custom module, in + one of the following formats: - - ``organizations/{organization}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. - - ``folders/{folder}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. - - ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. + - ``organizations/{organization}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1908,8 +1905,9 @@ def simulate_security_health_analytics_custom_module( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.SimulateSecurityHealthAnalyticsCustomModuleResponse: - r"""Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. + r"""Simulates the result of using a + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + to check a resource. .. code-block:: python @@ -1943,16 +1941,15 @@ def sample_simulate_security_health_analytics_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.SimulateSecurityHealthAnalyticsCustomModuleRequest, dict]): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. + The request object. Request message for + [SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule]. + The maximum size of the request is 4 MiB. parent (str): Required. The relative resource name of the organization, project, or folder. For more information - about relative resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}``. + about relative resource names, see `AIP-122: Resource + names `__. Example: + ``organizations/{organization_id}``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1979,8 +1976,8 @@ def sample_simulate_security_health_analytics_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a SecurityHealthAnalyticsCustomModule - against a given resource. + Response message for + [SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule]. """ # Create or coerce a protobuf request object. @@ -2085,14 +2082,15 @@ def sample_list_effective_event_threat_detection_custom_modules(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.ListEffectiveEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request message for listing effective - Event Threat Detection custom modules. + The request object. Request message for + [SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules]. parent (str): Required. Name of parent to list effective custom - modules. Its format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + modules, in one of the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -2105,13 +2103,11 @@ def sample_list_effective_event_threat_detection_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListEffectiveEventThreatDetectionCustomModulesPager: - Response message for listing - effective Event Threat Detection custom - modules. + Response message for + [SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules]. - Iterating over this object will yield - results and resolve additional pages - automatically. + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -2189,14 +2185,20 @@ def get_effective_event_threat_detection_custom_module( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.EffectiveEventThreatDetectionCustomModule: - r"""Gets an effective ETD custom module. Retrieves the effective - module at the given level. The difference between an - EffectiveCustomModule and a CustomModule is that the fields for - an EffectiveCustomModule are computed from ancestors if needed. - For example, the enablement_state for a CustomModule can be - either ENABLED, DISABLED, or INHERITED. Where as the - enablement_state for an EffectiveCustomModule is always computed - to ENABLED or DISABLED (the effective enablement_state). + r"""Gets the effective Event Threat Detection custom module at the + given level. + + The difference between an + [EffectiveEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EffectiveEventThreatDetectionCustomModule] + and an + [EventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule] + is that the fields for an + ``EffectiveEventThreatDetectionCustomModule`` are computed from + ancestors if needed. For example, the enablement state for an + ``EventThreatDetectionCustomModule`` can be ``ENABLED``, + ``DISABLED``, or ``INHERITED``. In contrast, the enablement + state for an ``EffectiveEventThreatDetectionCustomModule`` is + always computed as ``ENABLED`` or ``DISABLED``. .. code-block:: python @@ -2226,16 +2228,16 @@ def sample_get_effective_event_threat_detection_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.GetEffectiveEventThreatDetectionCustomModuleRequest, dict]): - The request object. Message for getting a - EffectiveEventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEffectiveEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEffectiveEventThreatDetectionCustomModule]. name (str): - Required. The resource name of the ETD custom module. - - Its format is: + Required. The resource name of the Event Threat + Detection custom module, in one of the following + formats: - - ``organizations/{organization}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2248,17 +2250,16 @@ def sample_get_effective_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the representation of - EventThreatDetectionCustomModule at a given level - taking hierarchy into account and resolving various - fields accordingly. e.g. if the module is enabled at - the ancestor level, effective modules at all - descendant levels will have enablement_state set to - ENABLED. Similarly, if module.inherited is set, then - effective module's config will contain the ancestor's - config details. - EffectiveEventThreatDetectionCustomModule is - read-only. + The representation of an + [EventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule] + at a given level, taking hierarchy into account and + resolving various fields accordingly. For example, if + the module is enabled at the ancestor level, then + effective modules at all descendant levels will have + their enablement state set to ENABLED. Similarly, if + module.inherited is set, then the effective module's + configuration will reflect the ancestor's + configuration. """ # Create or coerce a protobuf request object. @@ -2326,9 +2327,9 @@ def list_event_threat_detection_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListEventThreatDetectionCustomModulesPager: r"""Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. + the given organization, folder, or project. This + includes resident modules defined at the scope of the + parent along with modules inherited from ancestors. .. code-block:: python @@ -2359,14 +2360,15 @@ def sample_list_event_threat_detection_custom_modules(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.ListEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request message for listing Event - Threat Detection custom modules. + The request object. Request message for + [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules]. parent (str): - Required. Name of parent to list custom modules. Its - format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent to list custom modules, in one + of the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -2379,11 +2381,11 @@ def sample_list_event_threat_detection_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListEventThreatDetectionCustomModulesPager: - Response message for listing Event - Threat Detection custom modules. - Iterating over this object will yield - results and resolve additional pages - automatically. + Response message for + [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules]. + + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -2464,8 +2466,8 @@ def list_descendant_event_threat_detection_custom_modules( metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDescendantEventThreatDetectionCustomModulesPager: r"""Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. + modules for the given organization, folder, or project + and its descendants. .. code-block:: python @@ -2496,15 +2498,15 @@ def sample_list_descendant_event_threat_detection_custom_modules(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.ListDescendantEventThreatDetectionCustomModulesRequest, dict]): - The request object. Request message for listing - descendant Event Threat Detection custom - modules. + The request object. Request message for + [SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules]. parent (str): - Required. Name of parent to list custom modules. Its - format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent to list custom modules, in one + of the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -2517,13 +2519,11 @@ def sample_list_descendant_event_threat_detection_custom_modules(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListDescendantEventThreatDetectionCustomModulesPager: - Response message for listing - descendant Event Threat Detection custom - modules. + Response message for + [SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules]. - Iterating over this object will yield - results and resolve additional pages - automatically. + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -2631,16 +2631,16 @@ def sample_get_event_threat_detection_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.GetEventThreatDetectionCustomModuleRequest, dict]): - The request object. Message for getting a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEventThreatDetectionCustomModule]. name (str): - Required. The resource name of the ETD custom module. - - Its format is: + Required. The resource name of the Event Threat + Detection custom module, in one of the following + formats: - - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2653,12 +2653,12 @@ def sample_get_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ # Create or coerce a protobuf request object. @@ -2731,9 +2731,9 @@ def create_event_threat_detection_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> security_center_management.EventThreatDetectionCustomModule: r"""Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are + module at the scope of the given organization, folder, + or project, and creates inherited custom modules for all + descendants of the given parent. These modules are enabled by default. .. code-block:: python @@ -2764,21 +2764,24 @@ def sample_create_event_threat_detection_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.CreateEventThreatDetectionCustomModuleRequest, dict]): - The request object. Message for creating a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.CreateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.CreateEventThreatDetectionCustomModule]. parent (str): - Required. Name of parent for the module. Its format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent for the module, in one of the + following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. event_threat_detection_custom_module (google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule): Required. The module to create. The - event_threat_detection_custom_module.name will be - ignored and server generated. + [EventThreatDetectionCustomModule.name][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule.name] + field is ignored; Security Command Center generates the + name. This corresponds to the ``event_threat_detection_custom_module`` field on the ``request`` instance; if ``request`` is provided, this @@ -2791,12 +2794,12 @@ def sample_create_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ # Create or coerce a protobuf request object. @@ -2909,18 +2912,13 @@ def sample_update_event_threat_detection_custom_module(): The request object. Message for updating a EventThreatDetectionCustomModule event_threat_detection_custom_module (google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule): - Required. The module being updated + Required. The module being updated. This corresponds to the ``event_threat_detection_custom_module`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Field mask is used to specify the fields to be - overwritten in the EventThreatDetectionCustomModule - resource by the update. The fields specified in the - update_mask are relative to the resource, not the full - request. A field will be overwritten if it is in the - mask. If the user does not provide a mask then all - fields will be overwritten. + Required. The fields to update. If + omitted, then all fields are updated. This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this @@ -2933,12 +2931,12 @@ def sample_update_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ # Create or coerce a protobuf request object. @@ -3017,9 +3015,9 @@ def delete_event_threat_detection_custom_module( metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. + module and all of its descendants in the resource + hierarchy. This method is only supported for resident + custom modules. .. code-block:: python @@ -3046,16 +3044,16 @@ def sample_delete_event_threat_detection_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.DeleteEventThreatDetectionCustomModuleRequest, dict]): - The request object. Message for deleting a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.DeleteEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.DeleteEventThreatDetectionCustomModule]. name (str): - Required. The resource name of the ETD custom module. - - Its format is: + Required. The resource name of the Event Threat + Detection custom module, in one of the following + formats: - - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -3159,8 +3157,8 @@ def sample_validate_event_threat_detection_custom_module(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.ValidateEventThreatDetectionCustomModuleRequest, dict]): - The request object. Request to validate an Event Threat - Detection custom module. + The request object. Request message for + [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3169,8 +3167,8 @@ def sample_validate_event_threat_detection_custom_module(): Returns: google.cloud.securitycentermanagement_v1.types.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. + Response message for + [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule]. """ # Create or coerce a protobuf request object. @@ -3252,25 +3250,23 @@ def sample_get_security_center_service(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.GetSecurityCenterServiceRequest, dict]): - The request object. Request message for getting a - Security Command Center service. + The request object. Request message for + [SecurityCenterManagement.GetSecurityCenterService][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetSecurityCenterService]. name (str): Required. The Security Command Center service to - retrieve. - - Formats: + retrieve, in one of the following formats: - organizations/{organization}/locations/{location}/securityCenterServices/{service} - folders/{folder}/locations/{location}/securityCenterServices/{service} - projects/{project}/locations/{location}/securityCenterServices/{service} - The possible values for id {service} are: + The following values are valid for ``{service}``: - - container-threat-detection - - event-threat-detection - - security-health-analytics - - vm-threat-detection - - web-security-scanner + - ``container-threat-detection`` + - ``event-threat-detection`` + - ``security-health-analytics`` + - ``vm-threat-detection`` + - ``web-security-scanner`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -3291,8 +3287,8 @@ def sample_get_security_center_service(): configured at the organization, folder, or project level. Service settings at the organization or folder level are - inherited by those in child folders and - projects. + inherited by those in descendant folders + and projects. """ # Create or coerce a protobuf request object. @@ -3387,17 +3383,16 @@ def sample_list_security_center_services(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.ListSecurityCenterServicesRequest, dict]): - The request object. Request message for listing Security - Command Center services. + The request object. Request message for + [SecurityCenterManagement.ListSecurityCenterServices][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityCenterServices]. parent (str): Required. The name of the parent to list Security - Command Center services. - - Formats: + Command Center services, in one of the following + formats: - - organizations/{organization}/locations/{location} - - folders/{folder}/locations/{location} - - projects/{project}/locations/{location} + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -3410,11 +3405,11 @@ def sample_list_security_center_services(): Returns: google.cloud.securitycentermanagement_v1.services.security_center_management.pagers.ListSecurityCenterServicesPager: - Response message for listing Security - Command Center services. - Iterating over this object will yield - results and resolve additional pages - automatically. + Response message for + [SecurityCenterManagement.ListSecurityCenterServices][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityCenterServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. """ # Create or coerce a protobuf request object. @@ -3521,19 +3516,21 @@ def sample_update_security_center_service(): Args: request (Union[google.cloud.securitycentermanagement_v1.types.UpdateSecurityCenterServiceRequest, dict]): - The request object. Request message for updating a - Security Command Center service. + The request object. Request message for + [SecurityCenterManagement.UpdateSecurityCenterService][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.UpdateSecurityCenterService]. security_center_service (google.cloud.securitycentermanagement_v1.types.SecurityCenterService): Required. The updated service. This corresponds to the ``security_center_service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Possible + Required. The fields to update. Accepts the following values: - - "intended_enablement_state" - - "modules" + - ``intended_enablement_state`` + - ``modules`` + + If omitted, then all eligible fields are updated. This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this @@ -3554,8 +3551,8 @@ def sample_update_security_center_service(): configured at the organization, folder, or project level. Service settings at the organization or folder level are - inherited by those in child folders and - projects. + inherited by those in descendant folders + and projects. """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/grpc.py b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/grpc.py index 60fd72a2df6e..f24defbee76b 100644 --- a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/grpc.py +++ b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/grpc.py @@ -249,10 +249,11 @@ def list_effective_security_health_analytics_custom_modules( analytics custom modules method over gRPC. Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors (no descendants). + [EffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.EffectiveSecurityHealthAnalyticsCustomModule] + resources for the given parent. This includes resident modules + defined at the scope of the parent, and inherited modules, + inherited from ancestor organizations, folders, and projects (no + descendants). Returns: Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], @@ -287,7 +288,7 @@ def get_effective_security_health_analytics_custom_module( analytics custom module method over gRPC. Gets details of a single - EffectiveSecurityHealthAnalyticsCustomModule. + [EffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.EffectiveSecurityHealthAnalyticsCustomModule]. Returns: Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], @@ -320,10 +321,11 @@ def list_security_health_analytics_custom_modules( custom modules method over gRPC. Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors (no descendants). + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + resources for the given parent. This includes resident modules + defined at the scope of the parent, and inherited modules, + inherited from ancestor organizations, folders, and projects (no + descendants). Returns: Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], @@ -358,8 +360,9 @@ def list_descendant_security_health_analytics_custom_modules( health analytics custom modules method over gRPC. Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent's CRM descendants. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + resources under the given organization, folder, or project and + all of its descendants. Returns: Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], @@ -394,7 +397,8 @@ def get_security_health_analytics_custom_module( r"""Return a callable for the get security health analytics custom module method over gRPC. - Retrieves a SecurityHealthAnalyticsCustomModule. + Retrieves a + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule]. Returns: Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], @@ -427,11 +431,11 @@ def create_security_health_analytics_custom_module( analytics custom module method over gRPC. Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + at the scope of the given organization, folder, or project, and + also creates inherited ``SecurityHealthAnalyticsCustomModule`` + resources for all folders and projects that are descendants of + the given parent. These modules are enabled by default. Returns: Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], @@ -463,13 +467,13 @@ def update_security_health_analytics_custom_module( r"""Return a callable for the update security health analytics custom module method over gRPC. - Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. + Updates the + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + under the given name based on the given update mask. Updating + the enablement state is supported on both resident and inherited + modules (though resident modules cannot have an enablement state + of "inherited"). Updating the display name and custom + configuration of a module is supported on resident modules only. Returns: Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], @@ -502,9 +506,9 @@ def delete_security_health_analytics_custom_module( analytics custom module method over gRPC. Deletes the specified - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + and all of its descendants in the resource hierarchy. This + method is only supported for resident custom modules. Returns: Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], @@ -536,8 +540,9 @@ def simulate_security_health_analytics_custom_module( r"""Return a callable for the simulate security health analytics custom module method over gRPC. - Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. + Simulates the result of using a + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + to check a resource. Returns: Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], @@ -608,14 +613,20 @@ def get_effective_event_threat_detection_custom_module( r"""Return a callable for the get effective event threat detection custom module method over gRPC. - Gets an effective ETD custom module. Retrieves the effective - module at the given level. The difference between an - EffectiveCustomModule and a CustomModule is that the fields for - an EffectiveCustomModule are computed from ancestors if needed. - For example, the enablement_state for a CustomModule can be - either ENABLED, DISABLED, or INHERITED. Where as the - enablement_state for an EffectiveCustomModule is always computed - to ENABLED or DISABLED (the effective enablement_state). + Gets the effective Event Threat Detection custom module at the + given level. + + The difference between an + [EffectiveEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EffectiveEventThreatDetectionCustomModule] + and an + [EventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule] + is that the fields for an + ``EffectiveEventThreatDetectionCustomModule`` are computed from + ancestors if needed. For example, the enablement state for an + ``EventThreatDetectionCustomModule`` can be ``ENABLED``, + ``DISABLED``, or ``INHERITED``. In contrast, the enablement + state for an ``EffectiveEventThreatDetectionCustomModule`` is + always computed as ``ENABLED`` or ``DISABLED``. Returns: Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], @@ -648,9 +659,9 @@ def list_event_threat_detection_custom_modules( custom modules method over gRPC. Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. + the given organization, folder, or project. This + includes resident modules defined at the scope of the + parent along with modules inherited from ancestors. Returns: Callable[[~.ListEventThreatDetectionCustomModulesRequest], @@ -685,8 +696,8 @@ def list_descendant_event_threat_detection_custom_modules( detection custom modules method over gRPC. Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. + modules for the given organization, folder, or project + and its descendants. Returns: Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], @@ -751,9 +762,9 @@ def create_event_threat_detection_custom_module( custom module method over gRPC. Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are + module at the scope of the given organization, folder, + or project, and creates inherited custom modules for all + descendants of the given parent. These modules are enabled by default. Returns: @@ -826,9 +837,9 @@ def delete_event_threat_detection_custom_module( custom module method over gRPC. Deletes the specified Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. + module and all of its descendants in the resource + hierarchy. This method is only supported for resident + custom modules. Returns: Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], diff --git a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/grpc_asyncio.py b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/grpc_asyncio.py index 9fcaafb6b03f..4d376db16761 100644 --- a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/grpc_asyncio.py +++ b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/grpc_asyncio.py @@ -259,10 +259,11 @@ def list_effective_security_health_analytics_custom_modules( analytics custom modules method over gRPC. Returns a list of all - EffectiveSecurityHealthAnalyticsCustomModules for the - given parent. This includes resident modules defined at - the scope of the parent, and inherited modules, - inherited from CRM ancestors (no descendants). + [EffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.EffectiveSecurityHealthAnalyticsCustomModule] + resources for the given parent. This includes resident modules + defined at the scope of the parent, and inherited modules, + inherited from ancestor organizations, folders, and projects (no + descendants). Returns: Callable[[~.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest], @@ -299,7 +300,7 @@ def get_effective_security_health_analytics_custom_module( analytics custom module method over gRPC. Gets details of a single - EffectiveSecurityHealthAnalyticsCustomModule. + [EffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.EffectiveSecurityHealthAnalyticsCustomModule]. Returns: Callable[[~.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest], @@ -334,10 +335,11 @@ def list_security_health_analytics_custom_modules( custom modules method over gRPC. Returns a list of all - SecurityHealthAnalyticsCustomModules for the given - parent. This includes resident modules defined at the - scope of the parent, and inherited modules, inherited - from CRM ancestors (no descendants). + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + resources for the given parent. This includes resident modules + defined at the scope of the parent, and inherited modules, + inherited from ancestor organizations, folders, and projects (no + descendants). Returns: Callable[[~.ListSecurityHealthAnalyticsCustomModulesRequest], @@ -374,8 +376,9 @@ def list_descendant_security_health_analytics_custom_modules( health analytics custom modules method over gRPC. Returns a list of all resident - SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent's CRM descendants. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + resources under the given organization, folder, or project and + all of its descendants. Returns: Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], @@ -410,7 +413,8 @@ def get_security_health_analytics_custom_module( r"""Return a callable for the get security health analytics custom module method over gRPC. - Retrieves a SecurityHealthAnalyticsCustomModule. + Retrieves a + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule]. Returns: Callable[[~.GetSecurityHealthAnalyticsCustomModuleRequest], @@ -443,11 +447,11 @@ def create_security_health_analytics_custom_module( analytics custom module method over gRPC. Creates a resident - SecurityHealthAnalyticsCustomModule at the scope of the - given CRM parent, and also creates inherited - SecurityHealthAnalyticsCustomModules for all CRM - descendants of the given parent. These modules are - enabled by default. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + at the scope of the given organization, folder, or project, and + also creates inherited ``SecurityHealthAnalyticsCustomModule`` + resources for all folders and projects that are descendants of + the given parent. These modules are enabled by default. Returns: Callable[[~.CreateSecurityHealthAnalyticsCustomModuleRequest], @@ -479,13 +483,13 @@ def update_security_health_analytics_custom_module( r"""Return a callable for the update security health analytics custom module method over gRPC. - Updates the SecurityHealthAnalyticsCustomModule under - the given name based on the given update mask. Updating - the enablement state is supported on both resident and - inherited modules (though resident modules cannot have - an enablement state of "inherited"). Updating the - display name and custom config of a module is supported - on resident modules only. + Updates the + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + under the given name based on the given update mask. Updating + the enablement state is supported on both resident and inherited + modules (though resident modules cannot have an enablement state + of "inherited"). Updating the display name and custom + configuration of a module is supported on resident modules only. Returns: Callable[[~.UpdateSecurityHealthAnalyticsCustomModuleRequest], @@ -518,9 +522,9 @@ def delete_security_health_analytics_custom_module( analytics custom module method over gRPC. Deletes the specified - SecurityHealthAnalyticsCustomModule and all of its - descendants in the CRM hierarchy. This method is only - supported for resident custom modules. + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + and all of its descendants in the resource hierarchy. This + method is only supported for resident custom modules. Returns: Callable[[~.DeleteSecurityHealthAnalyticsCustomModuleRequest], @@ -554,8 +558,9 @@ def simulate_security_health_analytics_custom_module( r"""Return a callable for the simulate security health analytics custom module method over gRPC. - Simulates a given SecurityHealthAnalyticsCustomModule - and Resource. + Simulates the result of using a + [SecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityHealthAnalyticsCustomModule] + to check a resource. Returns: Callable[[~.SimulateSecurityHealthAnalyticsCustomModuleRequest], @@ -628,14 +633,20 @@ def get_effective_event_threat_detection_custom_module( r"""Return a callable for the get effective event threat detection custom module method over gRPC. - Gets an effective ETD custom module. Retrieves the effective - module at the given level. The difference between an - EffectiveCustomModule and a CustomModule is that the fields for - an EffectiveCustomModule are computed from ancestors if needed. - For example, the enablement_state for a CustomModule can be - either ENABLED, DISABLED, or INHERITED. Where as the - enablement_state for an EffectiveCustomModule is always computed - to ENABLED or DISABLED (the effective enablement_state). + Gets the effective Event Threat Detection custom module at the + given level. + + The difference between an + [EffectiveEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EffectiveEventThreatDetectionCustomModule] + and an + [EventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule] + is that the fields for an + ``EffectiveEventThreatDetectionCustomModule`` are computed from + ancestors if needed. For example, the enablement state for an + ``EventThreatDetectionCustomModule`` can be ``ENABLED``, + ``DISABLED``, or ``INHERITED``. In contrast, the enablement + state for an ``EffectiveEventThreatDetectionCustomModule`` is + always computed as ``ENABLED`` or ``DISABLED``. Returns: Callable[[~.GetEffectiveEventThreatDetectionCustomModuleRequest], @@ -670,9 +681,9 @@ def list_event_threat_detection_custom_modules( custom modules method over gRPC. Lists all Event Threat Detection custom modules for - the given Resource Manager parent. This includes - resident modules defined at the scope of the parent - along with modules inherited from ancestors. + the given organization, folder, or project. This + includes resident modules defined at the scope of the + parent along with modules inherited from ancestors. Returns: Callable[[~.ListEventThreatDetectionCustomModulesRequest], @@ -709,8 +720,8 @@ def list_descendant_event_threat_detection_custom_modules( detection custom modules method over gRPC. Lists all resident Event Threat Detection custom - modules under the given Resource Manager parent and its - descendants. + modules for the given organization, folder, or project + and its descendants. Returns: Callable[[~.ListDescendantEventThreatDetectionCustomModulesRequest], @@ -775,9 +786,9 @@ def create_event_threat_detection_custom_module( custom module method over gRPC. Creates a resident Event Threat Detection custom - module at the scope of the given Resource Manager - parent, and also creates inherited custom modules for - all descendants of the given parent. These modules are + module at the scope of the given organization, folder, + or project, and creates inherited custom modules for all + descendants of the given parent. These modules are enabled by default. Returns: @@ -850,9 +861,9 @@ def delete_event_threat_detection_custom_module( custom module method over gRPC. Deletes the specified Event Threat Detection custom - module and all of its descendants in the Resource - Manager hierarchy. This method is only supported for - resident custom modules. + module and all of its descendants in the resource + hierarchy. This method is only supported for resident + custom modules. Returns: Callable[[~.DeleteEventThreatDetectionCustomModuleRequest], diff --git a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/rest.py b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/rest.py index 1bc8b4496df6..750c72a082f5 100644 --- a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/rest.py +++ b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/services/security_center_management/transports/rest.py @@ -948,8 +948,8 @@ def __call__( Args: request (~.security_center_management.CreateEventThreatDetectionCustomModuleRequest): - The request object. Message for creating a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.CreateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.CreateEventThreatDetectionCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -958,12 +958,12 @@ def __call__( Returns: ~.security_center_management.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ @@ -1062,8 +1062,8 @@ def __call__( Args: request (~.security_center_management.CreateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Message for creating a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.CreateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.CreateSecurityHealthAnalyticsCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1080,7 +1080,7 @@ def __call__( the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -1181,8 +1181,8 @@ def __call__( Args: request (~.security_center_management.DeleteEventThreatDetectionCustomModuleRequest): - The request object. Message for deleting a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.DeleteEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.DeleteEventThreatDetectionCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1267,8 +1267,8 @@ def __call__( Args: request (~.security_center_management.DeleteSecurityHealthAnalyticsCustomModuleRequest): - The request object. Message for deleting a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.DeleteSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.DeleteSecurityHealthAnalyticsCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1353,8 +1353,8 @@ def __call__( Args: request (~.security_center_management.GetEffectiveEventThreatDetectionCustomModuleRequest): - The request object. Message for getting a - EffectiveEventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEffectiveEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEffectiveEventThreatDetectionCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1363,16 +1363,15 @@ def __call__( Returns: ~.security_center_management.EffectiveEventThreatDetectionCustomModule: - An EffectiveEventThreatDetectionCustomModule is the - representation of EventThreatDetectionCustomModule at a - given level taking hierarchy into account and resolving - various fields accordingly. e.g. if the module is - enabled at the ancestor level, effective modules at all - descendant levels will have enablement_state set to - ENABLED. Similarly, if module.inherited is set, then - effective module's config will contain the ancestor's - config details. - EffectiveEventThreatDetectionCustomModule is read-only. + The representation of an + [EventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule] + at a given level, taking hierarchy into account and + resolving various fields accordingly. For example, if + the module is enabled at the ancestor level, then + effective modules at all descendant levels will have + their enablement state set to ``ENABLED``. Similarly, if + ``module.inherited`` is set, then the effective module's + configuration will reflect the ancestor's configuration. """ @@ -1469,8 +1468,8 @@ def __call__( Args: request (~.security_center_management.GetEffectiveSecurityHealthAnalyticsCustomModuleRequest): - The request object. Message for getting a - EffectiveSecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEffectiveSecurityHealthAnalyticsCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1479,20 +1478,16 @@ def __call__( Returns: ~.security_center_management.EffectiveSecurityHealthAnalyticsCustomModule: - An EffectiveSecurityHealthAnalyticsCustomModule is the - representation of a Security Health Analytics custom + The representation of a Security Health Analytics custom module at a specified level of the resource hierarchy: organization, folder, or project. If a custom module is - inherited from a parent organization or folder, the - value of the ``enablementState`` property in - EffectiveSecurityHealthAnalyticsCustomModule is set to - the value that is effective in the parent, instead of - ``INHERITED``. For example, if the module is enabled in - a parent organization or folder, the effective - enablement_state for the module in all child folders or - projects is also ``enabled``. - EffectiveSecurityHealthAnalyticsCustomModule is - read-only. + inherited from an ancestor organization or folder, then + the enablement state is set to the value that is + effective in the parent, not to ``INHERITED``. For + example, if the module is enabled in an organization or + folder, then the effective enablement state for the + module is ``ENABLED`` in all descendant folders or + projects. """ @@ -1587,8 +1582,8 @@ def __call__( Args: request (~.security_center_management.GetEventThreatDetectionCustomModuleRequest): - The request object. Message for getting a - EventThreatDetectionCustomModule + The request object. Request message for + [SecurityCenterManagement.GetEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEventThreatDetectionCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1597,12 +1592,12 @@ def __call__( Returns: ~.security_center_management.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ @@ -1693,8 +1688,8 @@ def __call__( Args: request (~.security_center_management.GetSecurityCenterServiceRequest): - The request object. Request message for getting a - Security Command Center service. + The request object. Request message for + [SecurityCenterManagement.GetSecurityCenterService][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetSecurityCenterService]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1711,8 +1706,8 @@ def __call__( configured at the organization, folder, or project level. Service settings at the organization or folder level are - inherited by those in child folders and - projects. + inherited by those in descendant folders + and projects. """ @@ -1798,8 +1793,8 @@ def __call__( Args: request (~.security_center_management.GetSecurityHealthAnalyticsCustomModuleRequest): - The request object. Message for getting a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.GetSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetSecurityHealthAnalyticsCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1816,7 +1811,7 @@ def __call__( the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -1912,9 +1907,8 @@ def __call__( Args: request (~.security_center_management.ListDescendantEventThreatDetectionCustomModulesRequest): - The request object. Request message for listing - descendant Event Threat Detection custom - modules. + The request object. Request message for + [SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1923,9 +1917,8 @@ def __call__( Returns: ~.security_center_management.ListDescendantEventThreatDetectionCustomModulesResponse: - Response message for listing - descendant Event Threat Detection custom - modules. + Response message for + [SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules]. """ @@ -2022,9 +2015,8 @@ def __call__( Args: request (~.security_center_management.ListDescendantSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing - descendant Security Health Analytics - custom modules. + The request object. Request message for + [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2033,9 +2025,8 @@ def __call__( Returns: ~.security_center_management.ListDescendantSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing - descendant Security Health Analytics - custom modules. + Response message for + [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. """ @@ -2132,8 +2123,8 @@ def __call__( Args: request (~.security_center_management.ListEffectiveEventThreatDetectionCustomModulesRequest): - The request object. Request message for listing effective - Event Threat Detection custom modules. + The request object. Request message for + [SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2142,9 +2133,8 @@ def __call__( Returns: ~.security_center_management.ListEffectiveEventThreatDetectionCustomModulesResponse: - Response message for listing - effective Event Threat Detection custom - modules. + Response message for + [SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules]. """ @@ -2241,9 +2231,8 @@ def __call__( Args: request (~.security_center_management.ListEffectiveSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing effective - Security Health Analytics custom - modules. + The request object. Request message for + [SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2252,9 +2241,8 @@ def __call__( Returns: ~.security_center_management.ListEffectiveSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing - effective Security Health Analytics - custom modules. + Response message for + [SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules]. """ @@ -2349,8 +2337,8 @@ def __call__( Args: request (~.security_center_management.ListEventThreatDetectionCustomModulesRequest): - The request object. Request message for listing Event - Threat Detection custom modules. + The request object. Request message for + [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2359,8 +2347,8 @@ def __call__( Returns: ~.security_center_management.ListEventThreatDetectionCustomModulesResponse: - Response message for listing Event - Threat Detection custom modules. + Response message for + [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules]. """ @@ -2455,8 +2443,8 @@ def __call__( Args: request (~.security_center_management.ListSecurityCenterServicesRequest): - The request object. Request message for listing Security - Command Center services. + The request object. Request message for + [SecurityCenterManagement.ListSecurityCenterServices][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityCenterServices]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2465,8 +2453,8 @@ def __call__( Returns: ~.security_center_management.ListSecurityCenterServicesResponse: - Response message for listing Security - Command Center services. + Response message for + [SecurityCenterManagement.ListSecurityCenterServices][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityCenterServices]. """ @@ -2556,8 +2544,8 @@ def __call__( Args: request (~.security_center_management.ListSecurityHealthAnalyticsCustomModulesRequest): - The request object. Request message for listing Security - Health Analytics custom modules. + The request object. Request message for + [SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2566,8 +2554,8 @@ def __call__( Returns: ~.security_center_management.ListSecurityHealthAnalyticsCustomModulesResponse: - Response message for listing Security - Health Analytics custom modules. + Response message for + [SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules]. """ @@ -2665,10 +2653,9 @@ def __call__( Args: request (~.security_center_management.SimulateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Request message to simulate a - CustomConfig against a given test - resource. Maximum size of the request is - 4 MB by default. + The request object. Request message for + [SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule]. + The maximum size of the request is 4 MiB. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2677,9 +2664,8 @@ def __call__( Returns: ~.security_center_management.SimulateSecurityHealthAnalyticsCustomModuleResponse: - Response message for simulating a - ``SecurityHealthAnalyticsCustomModule`` against a given - resource. + Response message for + [SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule]. """ @@ -2792,12 +2778,12 @@ def __call__( Returns: ~.security_center_management.EventThreatDetectionCustomModule: - An event threat detection custom - module is a Cloud SCC resource that - contains the configuration and + A Security Command Center resource + that contains the configuration and enablement state of a custom module, - which enables ETD to write certain - findings to Cloud SCC. + which enables Event Threat Detection to + write certain findings to Security + Command Center. """ @@ -2896,8 +2882,8 @@ def __call__( Args: request (~.security_center_management.UpdateSecurityCenterServiceRequest): - The request object. Request message for updating a - Security Command Center service. + The request object. Request message for + [SecurityCenterManagement.UpdateSecurityCenterService][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.UpdateSecurityCenterService]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2914,8 +2900,8 @@ def __call__( configured at the organization, folder, or project level. Service settings at the organization or folder level are - inherited by those in child folders and - projects. + inherited by those in descendant folders + and projects. """ @@ -3007,8 +2993,8 @@ def __call__( Args: request (~.security_center_management.UpdateSecurityHealthAnalyticsCustomModuleRequest): - The request object. Message for updating a - SecurityHealthAnalyticsCustomModule + The request object. Request message for + [SecurityCenterManagement.UpdateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.UpdateSecurityHealthAnalyticsCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3025,7 +3011,7 @@ def __call__( the organization, folder, or project level. Custom modules that you create at the organization or folder level are - inherited by the child folders and + inherited by the descendant folders and projects. """ @@ -3129,8 +3115,8 @@ def __call__( Args: request (~.security_center_management.ValidateEventThreatDetectionCustomModuleRequest): - The request object. Request to validate an Event Threat - Detection custom module. + The request object. Request message for + [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3139,8 +3125,8 @@ def __call__( Returns: ~.security_center_management.ValidateEventThreatDetectionCustomModuleResponse: - Response to validating an Event - Threat Detection custom module. + Response message for + [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule]. """ diff --git a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/types/security_center_management.py b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/types/security_center_management.py index 49d0dff77c38..fafe93f6f078 100644 --- a/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/types/security_center_management.py +++ b/packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/types/security_center_management.py @@ -76,74 +76,73 @@ class SecurityCenterService(proto.Message): addition to individual module settings. Service settings can be configured at the organization, folder, or project level. Service settings at the organization or folder level are - inherited by those in child folders and projects. + inherited by those in descendant folders and projects. Attributes: name (str): - Identifier. The name of the service. - - Its format is: + Identifier. The name of the service, in one of the following + formats: - - organizations/{organization}/locations/{location}/securityCenterServices/{service} - - folders/{folder}/locations/{location}/securityCenterServices/{service} - - projects/{project}/locations/{location}/securityCenterServices/{service} + - ``organizations/{organization}/locations/{location}/securityCenterServices/{service}`` + - ``folders/{folder}/locations/{location}/securityCenterServices/{service}`` + - ``projects/{project}/locations/{location}/securityCenterServices/{service}`` - The possible values for id {service} are: + The following values are valid for ``{service}``: - - container-threat-detection - - event-threat-detection - - security-health-analytics - - vm-threat-detection - - web-security-scanner + - ``container-threat-detection`` + - ``event-threat-detection`` + - ``security-health-analytics`` + - ``vm-threat-detection`` + - ``web-security-scanner`` intended_enablement_state (google.cloud.securitycentermanagement_v1.types.SecurityCenterService.EnablementState): - Optional. The intended state of enablement for the service - at its level of the resource hierarchy. A DISABLED state - will override all module enablement_states to DISABLED. + Optional. The intended enablement state for the service at + its level of the resource hierarchy. A ``DISABLED`` state + will override all module enablement states to ``DISABLED``. effective_enablement_state (google.cloud.securitycentermanagement_v1.types.SecurityCenterService.EnablementState): - Output only. The effective enablement state - for the service at its level of the resource - hierarchy. If the intended state is set to - INHERITED, the effective state will be inherited - from the enablement state of an ancestor. This - state may differ from the intended enablement - state due to billing eligibility or onboarding - status. + Output only. The effective enablement state for the service + at its level of the resource hierarchy. If the intended + state is set to ``INHERITED``, the effective state will be + inherited from the enablement state of an ancestor. This + state may differ from the intended enablement state due to + billing eligibility or onboarding status. modules (MutableMapping[str, google.cloud.securitycentermanagement_v1.types.SecurityCenterService.ModuleSettings]): - Optional. The configurations including the - state of enablement for the service's different + Optional. The module configurations, + including the enablement state for the service's modules. The absence of a module in the map - implies its configuration is inherited from its - parents. + implies that its configuration is inherited from + its parents. update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time the service was last updated. This could be due to an explicit user update or due to a side effect of another system - change such as billing subscription expiry. + change, such as billing subscription expiry. service_config (google.protobuf.struct_pb2.Struct): - Optional. Additional service specific + Optional. Additional service-specific configuration. Not all services will utilize this field. """ class EnablementState(proto.Enum): - r"""Represents the possible intended states of enablement for a - service or module. + r"""Represents the possible enablement states for a service or + module. Values: ENABLEMENT_STATE_UNSPECIFIED (0): Default value. This value is unused. INHERITED (1): State is inherited from the parent resource. - Not a valid effective enablement state. + Valid as an intended enablement state, but not + as an effective enablement state. ENABLED (2): State is enabled. DISABLED (3): State is disabled. INGEST_ONLY (4): - SCC is configured to ingest findings from this service but - not enable this service. Not a valid - intended_enablement_state (that is, this is a readonly - state). + Security Command Center is configured to + ingest findings from this service, but not to + enable this service. This state indicates that + Security Command Center is misconfigured. You + can't set this state yourself. """ ENABLEMENT_STATE_UNSPECIFIED = 0 INHERITED = 1 @@ -156,17 +155,15 @@ class ModuleSettings(proto.Message): Attributes: intended_enablement_state (google.cloud.securitycentermanagement_v1.types.SecurityCenterService.EnablementState): - Optional. The intended state of enablement - for the module at its level of the resource + Optional. The intended enablement state for + the module at its level of the resource hierarchy. effective_enablement_state (google.cloud.securitycentermanagement_v1.types.SecurityCenterService.EnablementState): - Output only. The effective enablement state - for the module at its level of the resource - hierarchy. If the intended state is set to - INHERITED, the effective state will be inherited - from the enablement state of an ancestor. This - state may - differ from the intended enablement state due to + Output only. The effective enablement state for the module + at its level of the resource hierarchy. If the intended + state is set to ``INHERITED``, the effective state will be + inherited from the enablement state of an ancestor. This + state may differ from the intended enablement state due to billing eligibility or onboarding status. """ @@ -218,33 +215,30 @@ class ModuleSettings(proto.Message): class EffectiveSecurityHealthAnalyticsCustomModule(proto.Message): - r"""An EffectiveSecurityHealthAnalyticsCustomModule is the - representation of a Security Health Analytics custom module at a + r"""The representation of a Security Health Analytics custom module at a specified level of the resource hierarchy: organization, folder, or - project. If a custom module is inherited from a parent organization - or folder, the value of the ``enablementState`` property in - EffectiveSecurityHealthAnalyticsCustomModule is set to the value - that is effective in the parent, instead of ``INHERITED``. For - example, if the module is enabled in a parent organization or - folder, the effective enablement_state for the module in all child - folders or projects is also ``enabled``. - EffectiveSecurityHealthAnalyticsCustomModule is read-only. + project. If a custom module is inherited from an ancestor + organization or folder, then the enablement state is set to the + value that is effective in the parent, not to ``INHERITED``. For + example, if the module is enabled in an organization or folder, then + the effective enablement state for the module is ``ENABLED`` in all + descendant folders or projects. Attributes: name (str): - Identifier. The full resource name of the custom module, - specified in one of the following formats: + Identifier. The full resource name of the custom module, in + one of the following formats: - - ``organizations/organization/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` - - ``folders/folder/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` - - ``projects/project/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` + - ``organizations/organization/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` + - ``folders/folder/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` + - ``projects/project/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` custom_config (google.cloud.securitycentermanagement_v1.types.CustomConfig): Output only. The user-specified configuration for the module. enablement_state (google.cloud.securitycentermanagement_v1.types.EffectiveSecurityHealthAnalyticsCustomModule.EnablementState): - Output only. The effective state of - enablement for the module at the given level of - the hierarchy. + Output only. The effective enablement state + for the module at the given level of the + hierarchy. display_name (str): Output only. The display name for the custom module. The name must be between 1 and 128 @@ -258,7 +252,7 @@ class EnablementState(proto.Enum): Values: ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. + Default value. This value is unused. ENABLED (1): The module is enabled at the given level. DISABLED (2): @@ -289,24 +283,28 @@ class EnablementState(proto.Enum): class ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing effective Security Health - Analytics custom modules. + r"""Request message for + [SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules]. Attributes: parent (str): - Required. Name of parent to list effective custom modules. - specified in one of the following formats: + Required. Name of parent to list effective custom modules, + in one of the following formats: - ``organizations/{organization}/locations/{location}`` - - ``folders/{folder}/locations/{location}`` or - ``projects/{project}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` page_size (int): Optional. The maximum number of results to return in a single response. Default is 10, minimum is 1, maximum is 1000. page_token (str): - Optional. The value returned by the last call - indicating a continuation. + Optional. A pagination token returned from a + previous request. Provide this token to retrieve + the next page of results. + + When paginating, the rest of the request must + match the request that generated the page token. """ parent: str = proto.Field( @@ -324,16 +322,17 @@ class ListEffectiveSecurityHealthAnalyticsCustomModulesRequest(proto.Message): class ListEffectiveSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing effective Security Health - Analytics custom modules. + r"""Response message for + [SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveSecurityHealthAnalyticsCustomModules]. Attributes: effective_security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycentermanagement_v1.types.EffectiveSecurityHealthAnalyticsCustomModule]): - The list of - EffectiveSecurityHealthAnalyticsCustomModule + The list of effective Security Health + Analytics custom modules. next_page_token (str): - A token identifying a page of results the - server should return. + A pagination token. To retrieve the next page + of results, call the method again with this + token. """ @property @@ -354,17 +353,17 @@ def raw_page(self): class GetEffectiveSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Message for getting a - EffectiveSecurityHealthAnalyticsCustomModule + r"""Request message for + [SecurityCenterManagement.GetEffectiveSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEffectiveSecurityHealthAnalyticsCustomModule]. Attributes: name (str): Required. The full resource name of the custom module, specified in one of the following formats: - - ``organizations/organization/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` - - ``folders/folder/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` - - ``projects/project/{location}/effectiveSecurityHealthAnalyticsCustomModules/{effective_security_health_analytics_custom_module}`` + - ``organizations/organization/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` + - ``folders/folder/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` + - ``projects/project/{location}/effectiveSecurityHealthAnalyticsCustomModules/{custom_module}`` """ name: str = proto.Field( @@ -379,16 +378,16 @@ class SecurityHealthAnalyticsCustomModule(proto.Message): state, and last updated time. You can create a custom module at the organization, folder, or project level. Custom modules that you create at the organization or folder level are inherited by - the child folders and projects. + the descendant folders and projects. Attributes: name (str): - Identifier. The full resource name of the custom module, - specified in one of the following formats: + Identifier. The full resource name of the custom module, in + one of the following formats: - - ``organizations/{organization}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}`` - - ``folders/{folder}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}`` - - ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}`` + - ``organizations/{organization}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` display_name (str): Optional. The display name of the Security Health Analytics custom module. This display @@ -415,7 +414,7 @@ class SecurityHealthAnalyticsCustomModule(proto.Message): or project in which you are viewing the custom module. custom_config (google.cloud.securitycentermanagement_v1.types.CustomConfig): - Optional. The user specified custom + Optional. The user-specified custom configuration for the module. """ @@ -424,20 +423,20 @@ class EnablementState(proto.Enum): Values: ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. + Default value. This value is unused. ENABLED (1): - The module is enabled at the given CRM - resource. + The module is enabled at the given + organization, folder, or project. DISABLED (2): - The module is disabled at the given CRM - resource. + The module is disabled at the given + organization, folder, or project. INHERITED (3): State is inherited from an ancestor module. The module will - either be effectively ENABLED or DISABLED based on its - closest non-inherited ancestor module in the CRM hierarchy. - Attempting to set a top level module (module with no parent) - to the INHERITED state will result in an INVALID_ARGUMENT - error. + either be effectively ``ENABLED`` or ``DISABLED`` based on + its closest non-inherited ancestor module in the resource + hierarchy. If you try to set a top-level module (a module + with no parent) to the ``INHERITED`` state, you receive an + ``INVALID_ARGUMENT`` error. """ ENABLEMENT_STATE_UNSPECIFIED = 0 ENABLED = 1 @@ -485,10 +484,9 @@ class CustomConfig(proto.Message): Attributes: predicate (google.type.expr_pb2.Expr): - Optional. The CEL expression to evaluate to - produce findings. When the expression evaluates - to true against a resource, a finding is - generated. + Optional. The Common Expression Language (CEL) expression to + evaluate to produce findings. When the expression evaluates + to ``true`` against a resource, a finding is generated. custom_output (google.cloud.securitycentermanagement_v1.types.CustomConfig.CustomOutputSpec): Optional. Custom output properties. resource_selector (google.cloud.securitycentermanagement_v1.types.CustomConfig.ResourceSelector): @@ -508,10 +506,10 @@ class CustomConfig(proto.Message): investigators understand the detected issue. The text must be enclosed in quotation marks. recommendation (str): - Optional. An explanation of the recommended steps that - security teams can take to resolve the detected issue. This - explanation is returned with each finding generated by this - module in the ``nextSteps`` property of the finding JSON. + Optional. An explanation of the recommended + steps that security teams can take to resolve + the detected issue. This explanation is returned + with each finding generated by this module. """ class Severity(proto.Enum): @@ -520,7 +518,7 @@ class Severity(proto.Enum): Values: SEVERITY_UNSPECIFIED (0): - Unspecified severity. + Default value. This value is unused. CRITICAL (1): Critical severity. HIGH (2): @@ -539,8 +537,8 @@ class Severity(proto.Enum): class CustomOutputSpec(proto.Message): r"""A set of optional name-value pairs that define custom source properties to return with each finding that is generated by the - custom module. The custom source properties that are defined here - are included in the finding JSON under ``sourceProperties``. + custom module. The custom source properties that are defined + here are included in the finding. Attributes: properties (MutableSequence[google.cloud.securitycentermanagement_v1.types.CustomConfig.CustomOutputSpec.Property]): @@ -626,13 +624,13 @@ class ResourceSelector(proto.Message): class ListSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing Security Health Analytics custom - modules. + r"""Request message for + [SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules]. Attributes: parent (str): - Required. Name of parent organization, folder, or project in - which to list custom modules, specified in one of the + Required. Name of the parent organization, folder, or + project in which to list custom modules, in one of the following formats: - ``organizations/{organization}/locations/{location}`` @@ -643,8 +641,12 @@ class ListSecurityHealthAnalyticsCustomModulesRequest(proto.Message): return in a single response. Default is 10, minimum is 1, maximum is 1000. page_token (str): - Optional. A token identifying a page of - results the server should return. + Optional. A pagination token returned from a + previous request. Provide this token to retrieve + the next page of results. + + When paginating, the rest of the request must + match the request that generated the page token. """ parent: str = proto.Field( @@ -662,16 +664,17 @@ class ListSecurityHealthAnalyticsCustomModulesRequest(proto.Message): class ListSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing Security Health Analytics custom - modules. + r"""Response message for + [SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityHealthAnalyticsCustomModules]. Attributes: security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycentermanagement_v1.types.SecurityHealthAnalyticsCustomModule]): - The list of - SecurityHealthAnalyticsCustomModules + The list of Security Health Analytics custom + modules. next_page_token (str): - A token identifying a page of results the - server should return. + A pagination token. To retrieve the next page + of results, call the method again with this + token. """ @property @@ -692,14 +695,14 @@ def raw_page(self): class ListDescendantSecurityHealthAnalyticsCustomModulesRequest(proto.Message): - r"""Request message for listing descendant Security Health - Analytics custom modules. + r"""Request message for + [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. Attributes: parent (str): Required. Name of the parent organization, folder, or - project in which to list custom modules, specified in one of - the following formats: + project in which to list custom modules, in one of the + following formats: - ``organizations/{organization}/locations/{location}`` - ``folders/{folder}/locations/{location}`` @@ -709,8 +712,12 @@ class ListDescendantSecurityHealthAnalyticsCustomModulesRequest(proto.Message): return in a single response. Default is 10, minimum is 1, maximum is 1000. page_token (str): - Optional. A token identifying a page of - results the server should return. + Optional. A pagination token returned from a + previous request. Provide this token to retrieve + the next page of results. + + When paginating, the rest of the request must + match the request that generated the page token. """ parent: str = proto.Field( @@ -728,16 +735,17 @@ class ListDescendantSecurityHealthAnalyticsCustomModulesRequest(proto.Message): class ListDescendantSecurityHealthAnalyticsCustomModulesResponse(proto.Message): - r"""Response message for listing descendant Security Health - Analytics custom modules. + r"""Response message for + [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. Attributes: security_health_analytics_custom_modules (MutableSequence[google.cloud.securitycentermanagement_v1.types.SecurityHealthAnalyticsCustomModule]): The list of SecurityHealthAnalyticsCustomModules next_page_token (str): - A token identifying a page of results the - server should return. + A pagination token. To retrieve the next page + of results, call the method again with this + token. """ @property @@ -758,11 +766,13 @@ def raw_page(self): class GetSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Message for getting a SecurityHealthAnalyticsCustomModule + r"""Request message for + [SecurityCenterManagement.GetSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetSecurityHealthAnalyticsCustomModule]. Attributes: name (str): - Required. Name of the resource + Required. Name of the resource, in the format + ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}``. """ name: str = proto.Field( @@ -772,30 +782,34 @@ class GetSecurityHealthAnalyticsCustomModuleRequest(proto.Message): class CreateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Message for creating a SecurityHealthAnalyticsCustomModule + r"""Request message for + [SecurityCenterManagement.CreateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.CreateSecurityHealthAnalyticsCustomModule]. Attributes: parent (str): Required. Name of the parent organization, folder, or - project of the module, specified in one of the following - formats: + project of the module, in one of the following formats: - ``organizations/{organization}/locations/{location}`` - ``folders/{folder}/locations/{location}`` - ``projects/{project}/locations/{location}`` security_health_analytics_custom_module (google.cloud.securitycentermanagement_v1.types.SecurityHealthAnalyticsCustomModule): - Required. The resource being created + Required. The resource being created. validate_only (bool): - Optional. When set to true, only validations - (including IAM checks) will done for the request - (no module will be created). An OK response - indicates the request is valid while an error - response indicates the request is invalid. Note - that a subsequent request to actually create the - module could still fail because: - - - The state could have changed (e.g. IAM permission lost) or - - A failure occurred during creation of the module. Defaults to false. + Optional. When set to ``true``, the request will be + validated (including IAM checks), but no module will be + created. An ``OK`` response indicates that the request is + valid, while an error response indicates that the request is + invalid. + + If the request is valid, a subsequent request to create the + module could still fail for one of the following reasons: + + - The state of your cloud resources changed; for example, + you lost a required IAM permission + - An error occurred during creation of the module + + Defaults to ``false``. """ parent: str = proto.Field( @@ -816,28 +830,36 @@ class CreateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): class UpdateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Message for updating a SecurityHealthAnalyticsCustomModule + r"""Request message for + [SecurityCenterManagement.UpdateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.UpdateSecurityHealthAnalyticsCustomModule]. Attributes: update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. The only fields - that can be updated are ``enablement_state`` and - ``custom_config``. If empty or set to the wildcard value - ``*``, both ``enablement_state`` and ``custom_config`` are - updated. + Required. The fields to update. The following values are + valid: + + - ``custom_config`` + - ``enablement_state`` + + If you omit this field or set it to the wildcard value + ``*``, then all eligible fields are updated. security_health_analytics_custom_module (google.cloud.securitycentermanagement_v1.types.SecurityHealthAnalyticsCustomModule): - Required. The resource being updated + Required. The resource being updated. validate_only (bool): - Optional. When set to true, only validations - (including IAM checks) will done for the request - (module will not be updated). An OK response - indicates the request is valid while an error - response indicates the request is invalid. Note - that a subsequent request to actually update the - module could still fail because - - - The state could have changed (e.g. IAM permission lost) or - - A failure occurred while trying to update the module. + Optional. When set to ``true``, the request will be + validated (including IAM checks), but no module will be + updated. An ``OK`` response indicates that the request is + valid, while an error response indicates that the request is + invalid. + + If the request is valid, a subsequent request to update the + module could still fail for one of the following reasons: + + - The state of your cloud resources changed; for example, + you lost a required IAM permission + - An error occurred during creation of the module + + Defaults to ``false``. """ update_mask: field_mask_pb2.FieldMask = proto.Field( @@ -859,28 +881,32 @@ class UpdateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): class DeleteSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Message for deleting a SecurityHealthAnalyticsCustomModule + r"""Request message for + [SecurityCenterManagement.DeleteSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.DeleteSecurityHealthAnalyticsCustomModule]. Attributes: name (str): - Required. The resource name of the SHA custom module. - - Its format is: + Required. The resource name of the SHA custom module, in one + of the following formats: - - ``organizations/{organization}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. - - ``folders/{folder}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. - - ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{security_health_analytics_custom_module}``. + - ``organizations/{organization}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/securityHealthAnalyticsCustomModules/{custom_module}`` validate_only (bool): - Optional. When set to true, only validations - (including IAM checks) will done for the request - (module will not be deleted). An OK response - indicates the request is valid while an error - response indicates the request is invalid. Note - that a subsequent request to actually delete the - module could still fail because - - - The state could have changed (e.g. IAM permission lost) or - - A failure occurred while trying to delete the module. + Optional. When set to ``true``, the request will be + validated (including IAM checks), but no module will be + deleted. An ``OK`` response indicates that the request is + valid, while an error response indicates that the request is + invalid. + + If the request is valid, a subsequent request to delete the + module could still fail for one of the following reasons: + + - The state of your cloud resources changed; for example, + you lost a required IAM permission + - An error occurred during deletion of the module + + Defaults to ``false``. """ name: str = proto.Field( @@ -894,16 +920,17 @@ class DeleteSecurityHealthAnalyticsCustomModuleRequest(proto.Message): class SimulateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): - r"""Request message to simulate a CustomConfig against a given - test resource. Maximum size of the request is 4 MB by default. + r"""Request message for + [SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule]. + The maximum size of the request is 4 MiB. Attributes: parent (str): Required. The relative resource name of the organization, project, or folder. For more information about relative - resource names, see `Relative Resource - Name `__ - Example: ``organizations/{organization_id}``. + resource names, see `AIP-122: Resource + names `__. Example: + ``organizations/{organization_id}``. custom_config (google.cloud.securitycentermanagement_v1.types.CustomConfig): Required. The custom configuration that you need to test. @@ -913,21 +940,24 @@ class SimulateSecurityHealthAnalyticsCustomModuleRequest(proto.Message): """ class SimulatedResource(proto.Message): - r"""Manually constructed resource name. If the custom module evaluates - against only the resource data, you can omit the ``iam_policy_data`` - field. If it evaluates only the ``iam_policy_data`` field, you can - omit the resource data. + r"""Manually constructed information about a resource. Attributes: resource_type (str): - Required. The type of the resource, for example, + Required. The type of the resource. For example, ``compute.googleapis.com/Disk``. resource_data (google.protobuf.struct_pb2.Struct): Optional. A representation of the Google Cloud resource. Should match the Google Cloud resource JSON format. + + If the custom module evaluates only the IAM + allow policy, then you can omit this field. iam_policy_data (google.iam.v1.policy_pb2.Policy): - Optional. A representation of the IAM policy. + Optional. A representation of the IAM allow + policy. + If the custom module evaluates only the resource + data, then you can omit this field. """ resource_type: str = proto.Field( @@ -962,54 +992,57 @@ class SimulatedResource(proto.Message): class SimulatedFinding(proto.Message): - r"""A subset of the fields of the Security Center Finding proto. - The minimum set of fields needed to represent a simulated - finding from a SHA custom module. + r"""The minimum set of fields needed to represent a simulated + finding from a Security Health Analytics custom module. Attributes: name (str): Identifier. The `relative resource - name `__ - of the finding. Example: - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}``, - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}``, - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}``. + name `__ of the finding, in one + of the following formats: + + - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - ``organizations/{organization_id}/sources/{source_id}`` - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. + The `relative resource name `__ + of the source the finding belongs to. For example, + ``organizations/{organization_id}/sources/{source_id}``. This field is immutable after creation time. + resource_name (str): + For findings on Google Cloud resources, the `full resource + name `__ of + the Google Cloud resource this finding is for. When the + finding is for a non-Google Cloud resource, the value can be + a customer or partner defined string. This field is + immutable after creation time. category (str): The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". + source. For example, ``XSS_FLASH_INJECTION``. This field is + immutable after creation time. state (google.cloud.securitycentermanagement_v1.types.SimulatedFinding.State): Output only. The state of the finding. source_properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. + Source-specific properties. These properties + are managed by the source that writes the + finding. The key names must be between 1 and 255 + characters; they must start with a letter and + contain alphanumeric characters or underscores + only. event_time (google.protobuf.timestamp_pb2.Timestamp): The time the finding was first detected. If an existing finding is updated, then this is the - time the update occurred. For example, if the - finding represents an open firewall, this - property captures the time the detector believes - the firewall became open. The accuracy is - determined by the detector. If the finding is + time the update occurred. If the finding is later resolved, then this time reflects when the - finding was resolved. This must not be set to a - value greater than the current timestamp. + finding was resolved. + + For example, if the finding represents an open + firewall, this property captures the time the + detector believes the firewall became open. The + accuracy is determined by the detector. + + The event time must not be set to a value + greater than the current timestamp. severity (google.cloud.securitycentermanagement_v1.types.SimulatedFinding.Severity): The severity of the finding. This field is managed by the source that writes the finding. @@ -1022,13 +1055,13 @@ class State(proto.Enum): Values: STATE_UNSPECIFIED (0): - Unspecified state. + Default value. This value is unused. ACTIVE (1): The finding requires attention and has not been addressed yet. INACTIVE (2): The finding has been fixed, triaged as a - non-issue or otherwise addressed and is no + non-issue, or otherwise addressed and is no longer active. """ STATE_UNSPECIFIED = 0 @@ -1040,82 +1073,67 @@ class Severity(proto.Enum): Values: SEVERITY_UNSPECIFIED (0): - This value is used for findings when a source - doesn't write a severity value. + Default value. This value is unused. CRITICAL (1): - Vulnerability: - - A critical vulnerability is easily discoverable - by an external actor, exploitable, and results - in the direct ability to execute arbitrary code, + For vulnerabilities: A critical vulnerability + is easily discoverable by an external actor, + exploitable, and results in the direct ability + to execute arbitrary code, exfiltrate data, and + otherwise gain additional access and privileges + to cloud resources and workloads. Examples + include publicly accessible unprotected user + data and public SSH access with weak or no + passwords. + + For threats: Indicates a threat that is able to + access, modify, or delete data or execute + unauthorized code within existing resources. + HIGH (2): + For vulnerabilities: A high-risk + vulnerability can be easily discovered and + exploited in combination with other + vulnerabilities in order to gain direct access + and the ability to execute arbitrary code, exfiltrate data, and otherwise gain additional access and privileges to cloud resources and - workloads. Examples include publicly accessible - unprotected user data and public SSH access with - weak or no passwords. - - Threat: - - Indicates a threat that is able to access, - modify, or delete data or execute unauthorized - code within existing resources. - HIGH (2): - Vulnerability: - - A high risk vulnerability can be easily - discovered and exploited in combination with - other vulnerabilities in order to gain direct - access and the ability to execute arbitrary - code, exfiltrate data, and otherwise gain - additional access and privileges to cloud - resources and workloads. An example is a - database with weak or no passwords that is only - accessible internally. This database could - easily be compromised by an actor that had - access to the internal network. - - Threat: - - Indicates a threat that is able to create new - computational resources in an environment but - not able to access data or execute code in - existing resources. + workloads. An example is a database with weak or + no passwords that is only accessible internally. + This database could easily be compromised by an + actor that had access to the internal network. + + For threats: Indicates a threat that is able to + create new computational resources in an + environment but not able to access data or + execute code in existing resources. MEDIUM (3): - Vulnerability: - - A medium risk vulnerability could be used by an - actor to gain access to resources or privileges - that enable them to eventually (through multiple - steps or a complex exploit) gain access and the - ability to execute arbitrary code or exfiltrate - data. An example is a service account with - access to more projects than it should have. If - an actor gains access to the service account, - they could potentially use that access to - manipulate a project the service account was not - intended to. - - Threat: - - Indicates a threat that is able to cause - operational impact but may not access data or - execute unauthorized code. + For vulnerabilities: A medium-risk + vulnerability could be used by an actor to gain + access to resources or privileges that enable + them to eventually (through multiple steps or a + complex exploit) gain access and the ability to + execute arbitrary code or exfiltrate data. An + example is a service account with access to more + projects than it should have. If an actor gains + access to the service account, they could + potentially use that access to manipulate a + project the service account was not intended to. + + For threats: Indicates a threat that is able to + cause operational impact but may not access data + or execute unauthorized code. LOW (4): - Vulnerability: - - A low risk vulnerability hampers a security - organization's ability to detect vulnerabilities - or active threats in their deployment, or - prevents the root cause investigation of - security issues. An example is monitoring and - logs being disabled for resource configurations - and access. - - Threat: - - Indicates a threat that has obtained minimal - access to an environment but is not able to - access data, execute code, or create resources. + For vulnerabilities: A low-risk vulnerability + hampers a security organization's ability to + detect vulnerabilities or active threats in + their deployment, or prevents the root cause + investigation of security issues. An example is + monitoring and logs being disabled for resource + configurations and access. + + For threats: Indicates a threat that has + obtained minimal access to an environment but is + not able to access data, execute code, or create + resources. """ SEVERITY_UNSPECIFIED = 0 CRITICAL = 1 @@ -1124,27 +1142,27 @@ class Severity(proto.Enum): LOW = 4 class FindingClass(proto.Enum): - r"""Represents what kind of Finding it is. + r"""Represents what kind of finding it is. Values: FINDING_CLASS_UNSPECIFIED (0): - Unspecified finding class. + Default value. This value is unused. THREAT (1): Describes unwanted or malicious activity. VULNERABILITY (2): Describes a potential weakness in software - that increases risk to Confidentiality & - Integrity & Availability. + that increases risk to confidentiality, + integrity, and availability. MISCONFIGURATION (3): Describes a potential weakness in cloud - resource/asset configuration that increases + resource or asset configuration that increases risk. OBSERVATION (4): Describes a security observation that is for informational purposes. SCC_ERROR (5): - Describes an error that prevents some SCC - functionality. + Describes an error that prevents Security + Command Center from working correctly. POSTURE_VIOLATION (6): Describes a potential security risk due to a change in the security posture. @@ -1207,8 +1225,8 @@ class FindingClass(proto.Enum): class SimulateSecurityHealthAnalyticsCustomModuleResponse(proto.Message): - r"""Response message for simulating a - ``SecurityHealthAnalyticsCustomModule`` against a given resource. + r"""Response message for + [SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.SimulateSecurityHealthAnalyticsCustomModule]. Attributes: result (google.cloud.securitycentermanagement_v1.types.SimulateSecurityHealthAnalyticsCustomModuleResponse.SimulatedResult): @@ -1229,7 +1247,7 @@ class SimulatedResult(proto.Message): Attributes: finding (google.cloud.securitycentermanagement_v1.types.SimulatedFinding): Finding that would be published for the test - case, if a violation is detected. + case if a violation is detected. This field is a member of `oneof`_ ``result``. no_violation (google.protobuf.empty_pb2.Empty): @@ -1270,37 +1288,38 @@ class SimulatedResult(proto.Message): class EffectiveEventThreatDetectionCustomModule(proto.Message): - r"""An EffectiveEventThreatDetectionCustomModule is the representation - of EventThreatDetectionCustomModule at a given level taking - hierarchy into account and resolving various fields accordingly. - e.g. if the module is enabled at the ancestor level, effective - modules at all descendant levels will have enablement_state set to - ENABLED. Similarly, if module.inherited is set, then effective - module's config will contain the ancestor's config details. - EffectiveEventThreatDetectionCustomModule is read-only. + r"""The representation of an + [EventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule] + at a given level, taking hierarchy into account and resolving + various fields accordingly. For example, if the module is enabled at + the ancestor level, then effective modules at all descendant levels + will have their enablement state set to ``ENABLED``. Similarly, if + ``module.inherited`` is set, then the effective module's + configuration will reflect the ancestor's configuration. Attributes: name (str): - Identifier. The resource name of the ETD custom module. + Identifier. The resource name of the Event Threat Detection + custom module, in one of the following formats: - Its format is: - - - ``organizations/{organization}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` config (google.protobuf.struct_pb2.Struct): - Output only. Config for the effective module. + Output only. Configuration for the effective + module. enablement_state (google.cloud.securitycentermanagement_v1.types.EffectiveEventThreatDetectionCustomModule.EnablementState): Output only. The effective state of enablement for the module at the given level of the hierarchy. type_ (str): - Output only. Type for the module. e.g. CONFIGURABLE_BAD_IP. + Output only. Type for the module (for example, + ``CONFIGURABLE_BAD_IP``). display_name (str): - Output only. The human readable name to be - displayed for the module. + Output only. The human-readable name of the + module. description (str): - Output only. The description for the module. + Output only. A description of the module. """ class EnablementState(proto.Enum): @@ -1308,7 +1327,7 @@ class EnablementState(proto.Enum): Values: ENABLEMENT_STATE_UNSPECIFIED (0): - Unspecified enablement state. + Default value. This value is unused. ENABLED (1): The module is enabled at the given level. DISABLED (2): @@ -1347,23 +1366,28 @@ class EnablementState(proto.Enum): class ListEffectiveEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request message for listing effective Event Threat Detection - custom modules. + r"""Request message for + [SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules]. Attributes: parent (str): - Required. Name of parent to list effective custom modules. - Its format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent to list effective custom modules, + in one of the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` page_size (int): Optional. The maximum number of results to return in a single response. Default is 10, minimum is 1, maximum is 1000. page_token (str): - Optional. The value returned by the last call - indicating a continuation + Optional. A pagination token returned from a + previous request. Provide this token to retrieve + the next page of results. + + When paginating, the rest of the request must + match the request that generated the page token. """ parent: str = proto.Field( @@ -1381,16 +1405,17 @@ class ListEffectiveEventThreatDetectionCustomModulesRequest(proto.Message): class ListEffectiveEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response message for listing effective Event Threat Detection - custom modules. + r"""Response message for + [SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEffectiveEventThreatDetectionCustomModules]. Attributes: effective_event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycentermanagement_v1.types.EffectiveEventThreatDetectionCustomModule]): - The list of - EffectiveEventThreatDetectionCustomModules + The list of effective Event Threat Detection + custom modules. next_page_token (str): - A token identifying a page of results the - server should return. + A pagination token. To retrieve the next page + of results, call the method again with this + token. """ @property @@ -1411,18 +1436,17 @@ def raw_page(self): class GetEffectiveEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Message for getting a - EffectiveEventThreatDetectionCustomModule + r"""Request message for + [SecurityCenterManagement.GetEffectiveEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEffectiveEventThreatDetectionCustomModule]. Attributes: name (str): - Required. The resource name of the ETD custom module. - - Its format is: + Required. The resource name of the Event Threat Detection + custom module, in one of the following formats: - - ``organizations/{organization}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/effectiveEventThreatDetectionCustomModules/{effective_event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/effectiveEventThreatDetectionCustomModules/{custom_module}`` """ name: str = proto.Field( @@ -1432,43 +1456,43 @@ class GetEffectiveEventThreatDetectionCustomModuleRequest(proto.Message): class EventThreatDetectionCustomModule(proto.Message): - r"""An event threat detection custom module is a Cloud SCC - resource that contains the configuration and enablement state of - a custom module, which enables ETD to write certain findings to - Cloud SCC. + r"""A Security Command Center resource that contains the + configuration and enablement state of a custom module, which + enables Event Threat Detection to write certain findings to + Security Command Center. Attributes: name (str): - Identifier. The resource name of the ETD custom module. - - Its format is: + Identifier. The resource name of the Event Threat Detection + custom module, in one of the following formats: - - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` config (google.protobuf.struct_pb2.Struct): - Optional. Config for the module. For the - resident module, its config value is defined at - this level. For the inherited module, its config - value is inherited from the ancestor module. + Optional. Configuration for the module. For + the resident module, its configuration value is + defined at this level. For the inherited module, + its configuration value is inherited from the + ancestor module. ancestor_module (str): Output only. The closest ancestor module that this module inherits the enablement state from. If empty, indicates that the custom module was created in the requesting parent organization, folder, or project. The format is the same as - the EventThreatDetectionCustomModule resource - name. + the custom module's resource name. enablement_state (google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule.EnablementState): Optional. The state of enablement for the module at the given level of the hierarchy. type_ (str): - Optional. Type for the module. e.g. CONFIGURABLE_BAD_IP. + Optional. Type for the module. For example, + ``CONFIGURABLE_BAD_IP``. display_name (str): - Optional. The human readable name to be - displayed for the module. + Optional. The human-readable name of the + module. description (str): - Optional. The description for the module. + Optional. A description of the module. update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time the module was last updated. @@ -1488,13 +1512,12 @@ class EnablementState(proto.Enum): DISABLED (2): The module is disabled at the given level. INHERITED (3): - State is inherited from an ancestor module. - The module will either be effectively ENABLED or - DISABLED based on its closest non-inherited - ancestor module in the CRM hierarchy. Attempting - to set a top level module (module with no - parent) to the INHERITED state will result in an - error. + State is inherited from an ancestor module. The module will + either be effectively ``ENABLED`` or ``DISABLED`` based on + its closest non-inherited ancestor module in the CRM + hierarchy. If you try to set a top-level module (a module + with no parent) to the ``INHERITED`` state, you receive an + ``INVALID_ARGUMENT`` error. """ ENABLEMENT_STATE_UNSPECIFIED = 0 ENABLED = 1 @@ -1543,29 +1566,30 @@ class EnablementState(proto.Enum): class ListEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request message for listing Event Threat Detection custom - modules. + r"""Request message for + [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules]. Attributes: parent (str): - Required. Name of parent to list custom modules. Its format - is ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent to list custom modules, in one of + the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` page_size (int): Optional. The maximum number of modules to return. The service may return fewer than this - value. If unspecified, at most 10 configs will + value. If unspecified, at most 10 modules will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. page_token (str): - Optional. A page token, received from a previous - ``ListEventThreatDetectionCustomModules`` call. Provide this - to retrieve the subsequent page. + Optional. A pagination token returned from a + previous request. Provide this token to retrieve + the next page of results. - When paginating, all other parameters provided to - ``ListEventThreatDetectionCustomModules`` must match the - call that provided the page token. + When paginating, the rest of the request must + match the request that generated the page token. """ parent: str = proto.Field( @@ -1583,15 +1607,16 @@ class ListEventThreatDetectionCustomModulesRequest(proto.Message): class ListEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response message for listing Event Threat Detection custom - modules. + r"""Response message for + [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules]. Attributes: event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule]): - The list of EventThreatDetectionCustomModules + The list of custom modules. next_page_token (str): - A token identifying a page of results the - server should return. + A pagination token. To retrieve the next page + of results, call the method again with this + token. """ @property @@ -1612,15 +1637,17 @@ def raw_page(self): class ListDescendantEventThreatDetectionCustomModulesRequest(proto.Message): - r"""Request message for listing descendant Event Threat Detection - custom modules. + r"""Request message for + [SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules]. Attributes: parent (str): - Required. Name of parent to list custom modules. Its format - is ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent to list custom modules, in one of + the following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` page_size (int): Optional. The maximum number of modules to return. The service may return fewer than this @@ -1628,8 +1655,12 @@ class ListDescendantEventThreatDetectionCustomModulesRequest(proto.Message): be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. page_token (str): - Optional. A token identifying a page of - results the server should return. + Optional. A pagination token returned from a + previous request. Provide this token to retrieve + the next page of results. + + When paginating, the rest of the request must + match the request that generated the page token. """ parent: str = proto.Field( @@ -1647,15 +1678,16 @@ class ListDescendantEventThreatDetectionCustomModulesRequest(proto.Message): class ListDescendantEventThreatDetectionCustomModulesResponse(proto.Message): - r"""Response message for listing descendant Event Threat - Detection custom modules. + r"""Response message for + [SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules]. Attributes: event_threat_detection_custom_modules (MutableSequence[google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule]): - The list of EventThreatDetectionCustomModules + The list of custom modules. next_page_token (str): - A token identifying a page of results the - server should return. + A pagination token. To retrieve the next page + of results, call the method again with this + token. """ @property @@ -1676,17 +1708,17 @@ def raw_page(self): class GetEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Message for getting a EventThreatDetectionCustomModule + r"""Request message for + [SecurityCenterManagement.GetEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetEventThreatDetectionCustomModule]. Attributes: name (str): - Required. The resource name of the ETD custom module. + Required. The resource name of the Event Threat Detection + custom module, in one of the following formats: - Its format is: - - - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` """ name: str = proto.Field( @@ -1696,29 +1728,37 @@ class GetEventThreatDetectionCustomModuleRequest(proto.Message): class CreateEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Message for creating a EventThreatDetectionCustomModule + r"""Request message for + [SecurityCenterManagement.CreateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.CreateEventThreatDetectionCustomModule]. Attributes: parent (str): - Required. Name of parent for the module. Its format is - ``organizations/{organization}/locations/{location}``, - ``folders/{folder}/locations/{location}``, or - ``projects/{project}/locations/{location}`` + Required. Name of parent for the module, in one of the + following formats: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` event_threat_detection_custom_module (google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule): Required. The module to create. The - event_threat_detection_custom_module.name will be ignored - and server generated. + [EventThreatDetectionCustomModule.name][google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule.name] + field is ignored; Security Command Center generates the + name. validate_only (bool): - Optional. When set to true, only validations - (including IAM checks) will done for the request - (no module will be created). An OK response - indicates the request is valid while an error - response indicates the request is invalid. Note - that a subsequent request to actually create the - module could still fail because - - - The state could have changed (e.g. IAM permission lost) or - - A failure occurred during creation of the module. + Optional. When set to ``true``, the request will be + validated (including IAM checks), but no module will be + created. An ``OK`` response indicates that the request is + valid, while an error response indicates that the request is + invalid. + + If the request is valid, a subsequent request to create the + module could still fail for one of the following reasons: + + - The state of your cloud resources changed; for example, + you lost a required IAM permission + - An error occurred during creation of the module + + Defaults to ``false``. """ parent: str = proto.Field( @@ -1743,25 +1783,25 @@ class UpdateEventThreatDetectionCustomModuleRequest(proto.Message): Attributes: update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Field mask is used to specify the fields to be - overwritten in the EventThreatDetectionCustomModule resource - by the update. The fields specified in the update_mask are - relative to the resource, not the full request. A field will - be overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. + Required. The fields to update. If omitted, + then all fields are updated. event_threat_detection_custom_module (google.cloud.securitycentermanagement_v1.types.EventThreatDetectionCustomModule): - Required. The module being updated + Required. The module being updated. validate_only (bool): - Optional. When set to true, only validations - (including IAM checks) will done for the request - (module will not be updated). An OK response - indicates the request is valid while an error - response indicates the request is invalid. Note - that a subsequent request to actually update the - module could still fail because - - - The state could have changed (e.g. IAM permission lost) or - - A failure occurred while trying to update the module. + Optional. When set to ``true``, the request will be + validated (including IAM checks), but no module will be + updated. An ``OK`` response indicates that the request is + valid, while an error response indicates that the request is + invalid. + + If the request is valid, a subsequent request to update the + module could still fail for one of the following reasons: + + - The state of your cloud resources changed; for example, + you lost a required IAM permission + - An error occurred during creation of the module + + Defaults to ``false``. """ update_mask: field_mask_pb2.FieldMask = proto.Field( @@ -1783,28 +1823,32 @@ class UpdateEventThreatDetectionCustomModuleRequest(proto.Message): class DeleteEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Message for deleting a EventThreatDetectionCustomModule + r"""Request message for + [SecurityCenterManagement.DeleteEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.DeleteEventThreatDetectionCustomModule]. Attributes: name (str): - Required. The resource name of the ETD custom module. - - Its format is: + Required. The resource name of the Event Threat Detection + custom module, in one of the following formats: - - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. - - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{event_threat_detection_custom_module}``. + - ``organizations/{organization}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``folders/{folder}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` + - ``projects/{project}/locations/{location}/eventThreatDetectionCustomModules/{custom_module}`` validate_only (bool): - Optional. When set to true, only validations - (including IAM checks) will done for the request - (module will not be deleted). An OK response - indicates the request is valid while an error - response indicates the request is invalid. Note - that a subsequent request to actually delete the - module could still fail because - - - The state could have changed (e.g. IAM permission lost) or - - A failure occurred while trying to delete the module. + Optional. When set to ``true``, the request will be + validated (including IAM checks), but no module will be + deleted. An ``OK`` response indicates that the request is + valid, while an error response indicates that the request is + invalid. + + If the request is valid, a subsequent request to delete the + module could still fail for one of the following reasons: + + - The state of your cloud resources changed; for example, + you lost a required IAM permission + - An error occurred during creation of the module + + Defaults to ``false``. """ name: str = proto.Field( @@ -1818,21 +1862,21 @@ class DeleteEventThreatDetectionCustomModuleRequest(proto.Message): class ValidateEventThreatDetectionCustomModuleRequest(proto.Message): - r"""Request to validate an Event Threat Detection custom module. + r"""Request message for + [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule]. Attributes: parent (str): - Required. Resource name of the parent to validate the Custom - Module under. + Required. Resource name of the parent to validate the custom + modules under, in one of the following formats: - Its format is: - - - ``organizations/{organization}/locations/{location}``. + - ``organizations/{organization}/locations/{location}`` raw_text (str): Required. The raw text of the module's contents. Used to generate error messages. type_ (str): - Required. The type of the module (e.g. CONFIGURABLE_BAD_IP). + Required. The type of the module. For example, + ``CONFIGURABLE_BAD_IP``. """ parent: str = proto.Field( @@ -1850,8 +1894,8 @@ class ValidateEventThreatDetectionCustomModuleRequest(proto.Message): class ValidateEventThreatDetectionCustomModuleResponse(proto.Message): - r"""Response to validating an Event Threat Detection custom - module. + r"""Response message for + [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule]. Attributes: errors (MutableSequence[google.cloud.securitycentermanagement_v1.types.ValidateEventThreatDetectionCustomModuleResponse.CustomModuleValidationError]): @@ -1861,31 +1905,31 @@ class ValidateEventThreatDetectionCustomModuleResponse(proto.Message): class CustomModuleValidationError(proto.Message): r"""An error encountered while validating the uploaded - configuration of an Event Threat Detection Custom Module. + configuration of an Event Threat Detection custom module. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: description (str): - A description of the error, suitable for - human consumption. Required. + A human-readable description of the error. field_path (str): - The path, in RFC 8901 JSON Pointer format, to - the field that failed validation. This may be - left empty if no specific field is affected. + The path, in `RFC 6901: JSON + Pointer `__ + format, to the field that failed validation. Omitted if no + specific field is affected. start (google.cloud.securitycentermanagement_v1.types.ValidateEventThreatDetectionCustomModuleResponse.Position): The initial position of the error in the - uploaded text version of the module. This field - may be omitted if no specific position applies, - or if one could not be computed. + uploaded text version of the module. Omitted if + no specific position applies, or if the position + could not be computed. This field is a member of `oneof`_ ``_start``. end (google.cloud.securitycentermanagement_v1.types.ValidateEventThreatDetectionCustomModuleResponse.Position): The end position of the error in the uploaded - text version of the module. This field may be - omitted if no specific position applies, or if - one could not be computed.. + text version of the module. Omitted if no + specific position applies, or if the position + could not be computed. This field is a member of `oneof`_ ``_end``. """ @@ -1918,9 +1962,9 @@ class Position(proto.Message): Attributes: line_number (int): - The line position in the text + The line position in the text. column_number (int): - The column position in the line + The column position in the line. """ line_number: int = proto.Field( @@ -1940,31 +1984,28 @@ class Position(proto.Message): class GetSecurityCenterServiceRequest(proto.Message): - r"""Request message for getting a Security Command Center - service. + r"""Request message for + [SecurityCenterManagement.GetSecurityCenterService][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.GetSecurityCenterService]. Attributes: name (str): - Required. The Security Command Center service to retrieve. - - Formats: + Required. The Security Command Center service to retrieve, + in one of the following formats: - organizations/{organization}/locations/{location}/securityCenterServices/{service} - folders/{folder}/locations/{location}/securityCenterServices/{service} - projects/{project}/locations/{location}/securityCenterServices/{service} - The possible values for id {service} are: + The following values are valid for ``{service}``: - - container-threat-detection - - event-threat-detection - - security-health-analytics - - vm-threat-detection - - web-security-scanner + - ``container-threat-detection`` + - ``event-threat-detection`` + - ``security-health-analytics`` + - ``vm-threat-detection`` + - ``web-security-scanner`` show_eligible_modules_only (bool): - Flag that, when set, will be used to filter - the ModuleSettings that are in scope. The - default setting is that all modules will be - shown. + Set to ``true`` to show only modules that are in scope. By + default, all modules are shown. """ name: str = proto.Field( @@ -1978,30 +2019,32 @@ class GetSecurityCenterServiceRequest(proto.Message): class ListSecurityCenterServicesRequest(proto.Message): - r"""Request message for listing Security Command Center services. + r"""Request message for + [SecurityCenterManagement.ListSecurityCenterServices][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityCenterServices]. Attributes: parent (str): Required. The name of the parent to list Security Command - Center services. - - Formats: + Center services, in one of the following formats: - - organizations/{organization}/locations/{location} - - folders/{folder}/locations/{location} - - projects/{project}/locations/{location} + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` page_size (int): Optional. The maximum number of results to return in a single response. Default is 10, minimum is 1, maximum is 1000. page_token (str): - Optional. The value returned by the last call - indicating a continuation. + Optional. A pagination token returned from a + previous request. Provide this token to retrieve + the next page of results. + + When paginating, the rest of the request must + match the request that generated the page token. show_eligible_modules_only (bool): - Flag that, when set, will be used to filter - the ModuleSettings that are in scope. The - default setting is that all modules will be - shown. + Flag that, when set, is used to filter the + module settings that are shown. The default + setting is that all modules are shown. """ parent: str = proto.Field( @@ -2023,15 +2066,16 @@ class ListSecurityCenterServicesRequest(proto.Message): class ListSecurityCenterServicesResponse(proto.Message): - r"""Response message for listing Security Command Center - services. + r"""Response message for + [SecurityCenterManagement.ListSecurityCenterServices][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListSecurityCenterServices]. Attributes: security_center_services (MutableSequence[google.cloud.securitycentermanagement_v1.types.SecurityCenterService]): The list of services. next_page_token (str): - A token identifying a page of results the - server should return. + A pagination token. To retrieve the next page + of results, call the method again with this + token. """ @property @@ -2052,31 +2096,35 @@ def raw_page(self): class UpdateSecurityCenterServiceRequest(proto.Message): - r"""Request message for updating a Security Command Center - service. + r"""Request message for + [SecurityCenterManagement.UpdateSecurityCenterService][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.UpdateSecurityCenterService]. Attributes: security_center_service (google.cloud.securitycentermanagement_v1.types.SecurityCenterService): Required. The updated service. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Possible values: + Required. The fields to update. Accepts the following + values: + + - ``intended_enablement_state`` + - ``modules`` - - "intended_enablement_state" - - "modules". + If omitted, then all eligible fields are updated. validate_only (bool): - Optional. When set to true, only validations - (including IAM checks) will be done for the - request (service will not be updated). An OK - response indicates that the request is valid, - while an error response indicates that the - request is invalid. Note that a subsequent - request to actually update the service could - still fail for one of the following reasons: - - - The state could have changed (e.g. IAM - permission lost). - - A failure occurred while trying to delete the - module. + Optional. When set to ``true``, the request will be + validated (including IAM checks), but no service will be + updated. An ``OK`` response indicates that the request is + valid, while an error response indicates that the request is + invalid. + + If the request is valid, a subsequent request to update the + service could still fail for one of the following reasons: + + - The state of your cloud resources changed; for example, + you lost a required IAM permission + - An error occurred during update of the service + + Defaults to ``false``. """ security_center_service: "SecurityCenterService" = proto.Field( diff --git a/packages/google-cloud-securitycentermanagement/samples/generated_samples/snippet_metadata_google.cloud.securitycentermanagement.v1.json b/packages/google-cloud-securitycentermanagement/samples/generated_samples/snippet_metadata_google.cloud.securitycentermanagement.v1.json index faf54288db7c..0924c1026372 100644 --- a/packages/google-cloud-securitycentermanagement/samples/generated_samples/snippet_metadata_google.cloud.securitycentermanagement.v1.json +++ b/packages/google-cloud-securitycentermanagement/samples/generated_samples/snippet_metadata_google.cloud.securitycentermanagement.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securitycentermanagement", - "version": "0.1.15" + "version": "0.1.16" }, "snippets": [ { diff --git a/packages/google-cloud-service-control/CHANGELOG.md b/packages/google-cloud-service-control/CHANGELOG.md index fd4a429000f7..43e5cc34ba35 100644 --- a/packages/google-cloud-service-control/CHANGELOG.md +++ b/packages/google-cloud-service-control/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.13.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-control-v1.13.0...google-cloud-service-control-v1.13.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([59c4287](https://github.com/googleapis/google-cloud-python/commit/59c42878386ee08d1717b73e47d33d76cfb38ba0)) + ## [1.13.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-control-v1.12.3...google-cloud-service-control-v1.13.0) (2024-10-24) diff --git a/packages/google-cloud-service-control/google/cloud/servicecontrol/gapic_version.py b/packages/google-cloud-service-control/google/cloud/servicecontrol/gapic_version.py index 43155ded0db3..0b9427f4e8a5 100644 --- a/packages/google-cloud-service-control/google/cloud/servicecontrol/gapic_version.py +++ b/packages/google-cloud-service-control/google/cloud/servicecontrol/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.0" # {x-release-please-version} +__version__ = "1.13.1" # {x-release-please-version} diff --git a/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/gapic_version.py b/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/gapic_version.py index 43155ded0db3..0b9427f4e8a5 100644 --- a/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/gapic_version.py +++ b/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.0" # {x-release-please-version} +__version__ = "1.13.1" # {x-release-please-version} diff --git a/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/services/quota_controller/client.py b/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/services/quota_controller/client.py index 8a1c74c9a86d..f1f3b71024f2 100644 --- a/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/services/quota_controller/client.py +++ b/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/services/quota_controller/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = QuotaControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or QuotaControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/services/service_controller/client.py b/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/services/service_controller/client.py index f99a8ec3700e..63aa5f6308ad 100644 --- a/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/services/service_controller/client.py +++ b/packages/google-cloud-service-control/google/cloud/servicecontrol_v1/services/service_controller/client.py @@ -442,36 +442,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ServiceControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -481,13 +451,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ServiceControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-service-control/google/cloud/servicecontrol_v2/gapic_version.py b/packages/google-cloud-service-control/google/cloud/servicecontrol_v2/gapic_version.py index 43155ded0db3..0b9427f4e8a5 100644 --- a/packages/google-cloud-service-control/google/cloud/servicecontrol_v2/gapic_version.py +++ b/packages/google-cloud-service-control/google/cloud/servicecontrol_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.0" # {x-release-please-version} +__version__ = "1.13.1" # {x-release-please-version} diff --git a/packages/google-cloud-service-control/google/cloud/servicecontrol_v2/services/service_controller/client.py b/packages/google-cloud-service-control/google/cloud/servicecontrol_v2/services/service_controller/client.py index b41b9b7e2d71..63bcc2b0db35 100644 --- a/packages/google-cloud-service-control/google/cloud/servicecontrol_v2/services/service_controller/client.py +++ b/packages/google-cloud-service-control/google/cloud/servicecontrol_v2/services/service_controller/client.py @@ -449,36 +449,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ServiceControllerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -488,13 +458,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ServiceControllerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-service-control/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json b/packages/google-cloud-service-control/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json index 8d8f03cb614e..55fc34ae7112 100644 --- a/packages/google-cloud-service-control/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json +++ b/packages/google-cloud-service-control/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-service-control", - "version": "1.13.0" + "version": "1.13.1" }, "snippets": [ { diff --git a/packages/google-cloud-service-control/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json b/packages/google-cloud-service-control/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json index 2d77f088d072..3d162977d48a 100644 --- a/packages/google-cloud-service-control/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json +++ b/packages/google-cloud-service-control/samples/generated_samples/snippet_metadata_google.api.servicecontrol.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-service-control", - "version": "1.13.0" + "version": "1.13.1" }, "snippets": [ { diff --git a/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py b/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py index 8080e06e8185..af10cf1c5fe2 100644 --- a/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py +++ b/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v1/test_quota_controller.py @@ -321,86 +321,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (QuotaControllerClient, transports.QuotaControllerGrpcTransport, "grpc"), - (QuotaControllerClient, transports.QuotaControllerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v1/test_service_controller.py b/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v1/test_service_controller.py index dc5681b9bfab..7b956b9019e1 100644 --- a/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v1/test_service_controller.py +++ b/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v1/test_service_controller.py @@ -340,86 +340,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v2/test_service_controller.py b/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v2/test_service_controller.py index c0674d15bf45..e1b67396dfdb 100644 --- a/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v2/test_service_controller.py +++ b/packages/google-cloud-service-control/tests/unit/gapic/servicecontrol_v2/test_service_controller.py @@ -332,86 +332,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ServiceControllerClient, transports.ServiceControllerGrpcTransport, "grpc"), - (ServiceControllerClient, transports.ServiceControllerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-service-management/CHANGELOG.md b/packages/google-cloud-service-management/CHANGELOG.md index fc8c1a475590..6e4a79beb199 100644 --- a/packages/google-cloud-service-management/CHANGELOG.md +++ b/packages/google-cloud-service-management/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-management-v1.10.0...google-cloud-service-management-v1.10.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([59c4287](https://github.com/googleapis/google-cloud-python/commit/59c42878386ee08d1717b73e47d33d76cfb38ba0)) + ## [1.10.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-management-v1.9.0...google-cloud-service-management-v1.10.0) (2024-10-24) diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement/gapic_version.py b/packages/google-cloud-service-management/google/cloud/servicemanagement/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement/gapic_version.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/gapic_version.py b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/gapic_version.py index d1d2a9e60a97..f1d827b5c728 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/gapic_version.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.0" # {x-release-please-version} +__version__ = "1.10.1" # {x-release-please-version} diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/client.py b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/client.py index f2c14f30c63c..43b423e379fd 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/client.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/client.py @@ -472,36 +472,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ServiceManagerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -511,13 +481,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ServiceManagerClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-service-management/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json b/packages/google-cloud-service-management/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json index 6c9297e2e994..2e4255955b65 100644 --- a/packages/google-cloud-service-management/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json +++ b/packages/google-cloud-service-management/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-service-management", - "version": "1.10.0" + "version": "1.10.1" }, "snippets": [ { diff --git a/packages/google-cloud-service-management/tests/unit/gapic/servicemanagement_v1/test_service_manager.py b/packages/google-cloud-service-management/tests/unit/gapic/servicemanagement_v1/test_service_manager.py index 35be99c0368e..1033aaf0d602 100644 --- a/packages/google-cloud-service-management/tests/unit/gapic/servicemanagement_v1/test_service_manager.py +++ b/packages/google-cloud-service-management/tests/unit/gapic/servicemanagement_v1/test_service_manager.py @@ -361,86 +361,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ServiceManagerClient, transports.ServiceManagerGrpcTransport, "grpc"), - (ServiceManagerClient, transports.ServiceManagerRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-service-usage/CHANGELOG.md b/packages/google-cloud-service-usage/CHANGELOG.md index 6e14e12fc9ec..f87091e03768 100644 --- a/packages/google-cloud-service-usage/CHANGELOG.md +++ b/packages/google-cloud-service-usage/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-usage-v1.11.0...google-cloud-service-usage-v1.11.1) (2024-10-31) + + +### Bug Fixes + +* disable universe-domain validation ([59c4287](https://github.com/googleapis/google-cloud-python/commit/59c42878386ee08d1717b73e47d33d76cfb38ba0)) + ## [1.11.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-usage-v1.10.5...google-cloud-service-usage-v1.11.0) (2024-10-24) diff --git a/packages/google-cloud-service-usage/google/cloud/service_usage/gapic_version.py b/packages/google-cloud-service-usage/google/cloud/service_usage/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-service-usage/google/cloud/service_usage/gapic_version.py +++ b/packages/google-cloud-service-usage/google/cloud/service_usage/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-service-usage/google/cloud/service_usage_v1/gapic_version.py b/packages/google-cloud-service-usage/google/cloud/service_usage_v1/gapic_version.py index 50d842f376d0..b50cada0b7ee 100644 --- a/packages/google-cloud-service-usage/google/cloud/service_usage_v1/gapic_version.py +++ b/packages/google-cloud-service-usage/google/cloud/service_usage_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.0" # {x-release-please-version} +__version__ = "1.11.1" # {x-release-please-version} diff --git a/packages/google-cloud-service-usage/google/cloud/service_usage_v1/services/service_usage/client.py b/packages/google-cloud-service-usage/google/cloud/service_usage_v1/services/service_usage/client.py index 909f3309f6fb..0e8fb1858e94 100644 --- a/packages/google-cloud-service-usage/google/cloud/service_usage_v1/services/service_usage/client.py +++ b/packages/google-cloud-service-usage/google/cloud/service_usage_v1/services/service_usage/client.py @@ -464,36 +464,6 @@ def _get_universe_domain( raise ValueError("Universe Domain cannot be an empty string.") return universe_domain - @staticmethod - def _compare_universes( - client_universe: str, credentials: ga_credentials.Credentials - ) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ServiceUsageClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default." - ) - return True - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -503,13 +473,9 @@ def _validate_universe_domain(self): Raises: ValueError: If the configured universe domain is not valid. """ - self._is_universe_domain_valid = ( - self._is_universe_domain_valid - or ServiceUsageClient._compare_universes( - self.universe_domain, self.transport._credentials - ) - ) - return self._is_universe_domain_valid + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True @property def api_endpoint(self): diff --git a/packages/google-cloud-service-usage/samples/generated_samples/snippet_metadata_google.api.serviceusage.v1.json b/packages/google-cloud-service-usage/samples/generated_samples/snippet_metadata_google.api.serviceusage.v1.json index a7af6fbb1341..ed52e7aa53a9 100644 --- a/packages/google-cloud-service-usage/samples/generated_samples/snippet_metadata_google.api.serviceusage.v1.json +++ b/packages/google-cloud-service-usage/samples/generated_samples/snippet_metadata_google.api.serviceusage.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-service-usage", - "version": "1.11.0" + "version": "1.11.1" }, "snippets": [ { diff --git a/packages/google-cloud-service-usage/tests/unit/gapic/service_usage_v1/test_service_usage.py b/packages/google-cloud-service-usage/tests/unit/gapic/service_usage_v1/test_service_usage.py index fe81b474bbe7..1393e986d6d3 100644 --- a/packages/google-cloud-service-usage/tests/unit/gapic/service_usage_v1/test_service_usage.py +++ b/packages/google-cloud-service-usage/tests/unit/gapic/service_usage_v1/test_service_usage.py @@ -313,86 +313,6 @@ def test__get_universe_domain(): assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (ServiceUsageClient, transports.ServiceUsageGrpcTransport, "grpc"), - (ServiceUsageClient, transports.ServiceUsageRestTransport, "rest"), - ], -) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel( - "http://localhost/", grpc.local_channel_credentials() - ) - transport = transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [ - int(part) for part in google.auth.__version__.split(".")[0:2] - ] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class(transport=transport_class(credentials=credentials)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [ - int(part) for part in api_core_version.__version__.split(".")[0:2] - ] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class( - client_options={"universe_domain": "bar.com"}, - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials(), - ), - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert ( - str(excinfo.value) - == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - ) - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - @pytest.mark.parametrize( "client_class,transport_name", [ diff --git a/packages/google-cloud-texttospeech/CHANGELOG.md b/packages/google-cloud-texttospeech/CHANGELOG.md index 16e43cf0da1e..0395e209fe75 100644 --- a/packages/google-cloud-texttospeech/CHANGELOG.md +++ b/packages/google-cloud-texttospeech/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-texttospeech/#history +## [2.21.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-texttospeech-v2.20.0...google-cloud-texttospeech-v2.21.0) (2024-10-31) + + +### Features + +* add multi-speaker markup, which allows generating dialogue between multiple speakers ([b01d99d](https://github.com/googleapis/google-cloud-python/commit/b01d99dc321be04b91dd183064bffdecfef9d5c0)) + ## [2.20.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-texttospeech-v2.19.0...google-cloud-texttospeech-v2.20.0) (2024-10-24) diff --git a/packages/google-cloud-texttospeech/google/cloud/texttospeech/__init__.py b/packages/google-cloud-texttospeech/google/cloud/texttospeech/__init__.py index ba526159493d..b3ce05f02d94 100644 --- a/packages/google-cloud-texttospeech/google/cloud/texttospeech/__init__.py +++ b/packages/google-cloud-texttospeech/google/cloud/texttospeech/__init__.py @@ -39,6 +39,7 @@ CustomVoiceParams, ListVoicesRequest, ListVoicesResponse, + MultiSpeakerMarkup, SsmlVoiceGender, StreamingSynthesisInput, StreamingSynthesizeConfig, @@ -69,6 +70,7 @@ "CustomVoiceParams", "ListVoicesRequest", "ListVoicesResponse", + "MultiSpeakerMarkup", "StreamingSynthesisInput", "StreamingSynthesizeConfig", "StreamingSynthesizeRequest", diff --git a/packages/google-cloud-texttospeech/google/cloud/texttospeech/gapic_version.py b/packages/google-cloud-texttospeech/google/cloud/texttospeech/gapic_version.py index 322be1a65464..ee3167621664 100644 --- a/packages/google-cloud-texttospeech/google/cloud/texttospeech/gapic_version.py +++ b/packages/google-cloud-texttospeech/google/cloud/texttospeech/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.20.0" # {x-release-please-version} +__version__ = "2.21.0" # {x-release-please-version} diff --git a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/__init__.py b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/__init__.py index c760b3e8a496..6fac6f5295a5 100644 --- a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/__init__.py +++ b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/__init__.py @@ -32,6 +32,7 @@ CustomVoiceParams, ListVoicesRequest, ListVoicesResponse, + MultiSpeakerMarkup, SsmlVoiceGender, StreamingSynthesisInput, StreamingSynthesizeConfig, @@ -61,6 +62,7 @@ "CustomVoiceParams", "ListVoicesRequest", "ListVoicesResponse", + "MultiSpeakerMarkup", "SsmlVoiceGender", "StreamingSynthesisInput", "StreamingSynthesizeConfig", diff --git a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/gapic_version.py b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/gapic_version.py index 322be1a65464..ee3167621664 100644 --- a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/gapic_version.py +++ b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.20.0" # {x-release-please-version} +__version__ = "2.21.0" # {x-release-please-version} diff --git a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/types/__init__.py b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/types/__init__.py index f27ec3967f33..884fecfd203e 100644 --- a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/types/__init__.py +++ b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/types/__init__.py @@ -22,6 +22,7 @@ CustomVoiceParams, ListVoicesRequest, ListVoicesResponse, + MultiSpeakerMarkup, SsmlVoiceGender, StreamingSynthesisInput, StreamingSynthesizeConfig, @@ -48,6 +49,7 @@ "CustomVoiceParams", "ListVoicesRequest", "ListVoicesResponse", + "MultiSpeakerMarkup", "StreamingSynthesisInput", "StreamingSynthesizeConfig", "StreamingSynthesizeRequest", diff --git a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/types/cloud_tts.py b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/types/cloud_tts.py index 37695bf7fe45..d1fe78111472 100644 --- a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/types/cloud_tts.py +++ b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1/types/cloud_tts.py @@ -31,6 +31,7 @@ "SynthesizeSpeechRequest", "CustomPronunciationParams", "CustomPronunciations", + "MultiSpeakerMarkup", "SynthesisInput", "VoiceSelectionParams", "AudioConfig", @@ -328,6 +329,42 @@ class CustomPronunciations(proto.Message): ) +class MultiSpeakerMarkup(proto.Message): + r"""A collection of turns for multi-speaker synthesis. + + Attributes: + turns (MutableSequence[google.cloud.texttospeech_v1.types.MultiSpeakerMarkup.Turn]): + Required. Speaker turns. + """ + + class Turn(proto.Message): + r"""A Multi-speaker turn. + + Attributes: + speaker (str): + Required. The speaker of the turn, for + example, 'O' or 'Q'. Please refer to + documentation for available speakers. + text (str): + Required. The text to speak. + """ + + speaker: str = proto.Field( + proto.STRING, + number=1, + ) + text: str = proto.Field( + proto.STRING, + number=2, + ) + + turns: MutableSequence[Turn] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Turn, + ) + + class SynthesisInput(proto.Message): r"""Contains text input to be synthesized. Either ``text`` or ``ssml`` must be supplied. Supplying both or neither returns @@ -354,6 +391,11 @@ class SynthesisInput(proto.Message): For more information, see `SSML `__. + This field is a member of `oneof`_ ``input_source``. + multi_speaker_markup (google.cloud.texttospeech_v1.types.MultiSpeakerMarkup): + The multi-speaker input to be synthesized. + Only applicable for multi-speaker synthesis. + This field is a member of `oneof`_ ``input_source``. custom_pronunciations (google.cloud.texttospeech_v1.types.CustomPronunciations): Optional. The pronunciation customizations to @@ -383,6 +425,12 @@ class SynthesisInput(proto.Message): number=2, oneof="input_source", ) + multi_speaker_markup: "MultiSpeakerMarkup" = proto.Field( + proto.MESSAGE, + number=4, + oneof="input_source", + message="MultiSpeakerMarkup", + ) custom_pronunciations: "CustomPronunciations" = proto.Field( proto.MESSAGE, number=3, diff --git a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1beta1/gapic_version.py b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1beta1/gapic_version.py index 322be1a65464..ee3167621664 100644 --- a/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1beta1/gapic_version.py +++ b/packages/google-cloud-texttospeech/google/cloud/texttospeech_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.20.0" # {x-release-please-version} +__version__ = "2.21.0" # {x-release-please-version} diff --git a/packages/google-cloud-texttospeech/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json b/packages/google-cloud-texttospeech/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json index e9241af986fc..9beea7aa0e4d 100644 --- a/packages/google-cloud-texttospeech/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json +++ b/packages/google-cloud-texttospeech/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-texttospeech", - "version": "2.20.0" + "version": "2.21.0" }, "snippets": [ { diff --git a/packages/google-cloud-texttospeech/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1beta1.json b/packages/google-cloud-texttospeech/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1beta1.json index e845eb27f948..bc5047ed6f65 100644 --- a/packages/google-cloud-texttospeech/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1beta1.json +++ b/packages/google-cloud-texttospeech/samples/generated_samples/snippet_metadata_google.cloud.texttospeech.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-texttospeech", - "version": "2.20.0" + "version": "2.21.0" }, "snippets": [ { diff --git a/scripts/client-post-processing/doc-formatting.yaml b/scripts/client-post-processing/doc-formatting.yaml index 332bb8ccb5b7..71b2ebb536c2 100644 --- a/scripts/client-post-processing/doc-formatting.yaml +++ b/scripts/client-post-processing/doc-formatting.yaml @@ -114,46 +114,6 @@ replacements: \ resource. Format: projects/\*/alertConfig after: " resource. Format: `projects/*/alertConfig`\n" count: 2 - - paths: [ - packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/types/security_center_management.py, - ] - before: | - \ 1. the state could have changed \(e.g. IAM - \ permission lost\) or - \ 2. A failure occurred during creation of the - \ module. Defaults to false. - after: " - The state could have changed (e.g. IAM permission lost) or\n - A failure occurred during creation of the module. Defaults to false.\n" - count: 1 - - paths: [ - packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/types/security_center_management.py, - ] - before: | - \ module could still fail because 1. the state - \ could have changed \(e.g. IAM permission lost\) or - \ 2. A failure occurred while trying to update the - \ module. - after: " module could still fail because\n\n - The state could have changed (e.g. IAM permission lost) or\n - A failure occurred while trying to update the module.\n" - count: 2 - - paths: [ - packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/types/security_center_management.py, - ] - before: | - \ module could still fail because 1. the state - \ could have changed \(e.g. IAM permission lost\) or - \ 2. A failure occurred while trying to delete the - \ module. - after: " module could still fail because\n\n - The state could have changed (e.g. IAM permission lost) or\n - A failure occurred while trying to delete the module.\n" - count: 2 - - paths: [ - packages/google-cloud-securitycentermanagement/google/cloud/securitycentermanagement_v1/types/security_center_management.py, - ] - before: | - \ module could still fail because 1. the state - \ could have changed \(e.g. IAM permission lost\) or - \ 2. A failure occurred during creation of the - \ module. - after: " module could still fail because\n\n - The state could have changed (e.g. IAM permission lost) or\n - A failure occurred during creation of the module.\n" - count: 1 - paths: [ packages/google-cloud-visionai/google/cloud/visionai_v1/types/platform.py, packages/google-cloud-visionai/google/cloud/visionai_v1alpha1/types/platform.py,